eframe/web/dropped_file.rs
1use core::{future::Future, pin::Pin};
2use std::path::{Path, PathBuf};
3
4use send_wrapper::SendWrapper;
5
6#[derive(Debug)]
7pub(crate) struct WebFile {
8 file: SendWrapper<web_sys::File>,
9 // We store a `PathBuf` here so that we can hand out `Path`s
10 // without allocating each time.
11 path: PathBuf,
12}
13
14impl From<web_sys::File> for WebFile {
15 fn from(file: web_sys::File) -> Self {
16 let path = file.name().into();
17 Self {
18 file: SendWrapper::new(file),
19 path,
20 }
21 }
22}
23
24impl egui::DroppedFile for WebFile {
25 fn path(&self) -> &Path {
26 &self.path
27 }
28
29 fn bytes_async(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, String>> + '_>> {
30 let file = web_sys::File::clone(&self.file);
31 Box::pin(async move {
32 if file.size() > f64::from(u32::MAX) {
33 return Err(format!(
34 "File is too large: browser file reads are limited to {} bytes",
35 u32::MAX
36 ));
37 }
38
39 let array_buffer = file
40 .array_buffer()
41 .await
42 .map_err(|err| crate::web::string_from_js_value(&err))?;
43 Ok(js_sys::Uint8Array::new(&array_buffer).to_vec())
44 })
45 }
46
47 fn web_file(&self) -> Option<&web_sys::File> {
48 Some(&*self.file)
49 }
50}