我设法使用以下方法获得了一个工作示例读取为二进制字符串 https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.FileReader.html#method.read_as_binary_string.
这是代码
lib.rs
use js_sys::JsString;
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{console, Event, FileReader, HtmlInputElement};
#[wasm_bindgen(start)]
pub fn main_wasm() {
let my_file: Rc<RefCell<Vec<u8>>> = Rc::new(RefCell::new(Vec::new()));
set_file_reader(&my_file);
}
fn set_file_reader(file: &Rc<RefCell<Vec<u8>>>) {
let filereader = FileReader::new().unwrap().dyn_into::<FileReader>().unwrap();
let my_file = Rc::clone(&file);
let onload = Closure::wrap(Box::new(move |event: Event| {
let element = event.target().unwrap().dyn_into::<FileReader>().unwrap();
let data = element.result().unwrap();
let file_string: JsString = data.dyn_into::<JsString>().unwrap();
let file_vec: Vec<u8> = file_string.iter().map(|x| x as u8).collect();
*my_file.borrow_mut() = file_vec;
console::log_1(&format!("file loaded: {:?}", file_string).into());
}) as Box<dyn FnMut(_)>);
filereader.set_onloadend(Some(onload.as_ref().unchecked_ref()));
onload.forget();
let fileinput: HtmlInputElement = web_sys::window()
.unwrap()
.document()
.expect("should have a document.")
.create_element("input")
.unwrap()
.dyn_into::<HtmlInputElement>()
.unwrap();
fileinput.set_id("file-upload");
fileinput.set_type("file");
web_sys::window()
.unwrap()
.document()
.unwrap()
.body()
.expect("document should have a body")
.append_child(&fileinput)
.unwrap();
let callback = Closure::wrap(Box::new(move |event: Event| {
let element = event
.target()
.unwrap()
.dyn_into::<HtmlInputElement>()
.unwrap();
let filelist = element.files().unwrap();
let _file = filelist.get(0).expect("should have a file handle.");
filereader.read_as_binary_string(&_file).unwrap();
}) as Box<dyn FnMut(_)>);
fileinput
.add_event_listener_with_callback("change", callback.as_ref().unchecked_ref())
.unwrap();
callback.forget();
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<noscript
>This page contains webassembly and javascript content, please enable
javascript in your browser.</noscript
>
<script src="./stack.js"></script>
<script>
wasm_bindgen("./stack_bg.wasm");
</script>
</body>
</html>
and the Cargo.toml
[package]
name = "stack"
version = "0.1.0"
authors = [""]
edition = "2018"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
js-sys = "0.3.55"
wee_alloc = { version = "0.4.2", optional = true }
[dependencies.web-sys]
version = "0.3.4"
features = [
'Document',
'Window',
'console',
'Event',
'FileReader',
'File',
'FileList',
'HtmlInputElement']
[dev-dependencies]
wasm-bindgen-test = "0.2"
[dependencies.wasm-bindgen]
version = "0.2.70"
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
debug = false
您可以检查此处的示例:http://rustwasmfileinput.glitch.me/ http://rustwasmfileinput.glitch.me/