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