dioxus/examples/file_upload.rs

77 lines
2.3 KiB
Rust
Raw Normal View History

2024-02-14 20:33:07 +00:00
//! This example shows how to use the `file` methods on FormEvent and DragEvent to handle file uploads and drops.
//!
//! Dioxus intercepts these events and provides a Rusty interface to the file data. Since we want this interface to
//! be crossplatform,
2024-01-08 22:08:21 +00:00
use dioxus::html::HasFileData;
2023-04-25 13:16:11 +00:00
use dioxus::prelude::*;
2023-06-05 08:47:04 +00:00
use tokio::time::sleep;
2023-04-25 13:16:11 +00:00
fn main() {
2024-02-14 20:33:07 +00:00
launch(app);
2023-04-25 13:16:11 +00:00
}
2024-02-14 20:33:07 +00:00
fn app() -> Element {
let mut enable_directory_upload = use_signal(|| false);
let mut files_uploaded = use_signal(|| Vec::new() as Vec<String>);
2024-01-15 21:06:05 +00:00
let upload_files = move |evt: FormEvent| async move {
for file_name in evt.files().unwrap().files() {
// no files on form inputs?
sleep(std::time::Duration::from_secs(1)).await;
files_uploaded.write().push(file_name);
}
};
let handle_file_drop = move |evt: DragEvent| async move {
if let Some(file_engine) = &evt.files() {
let files = file_engine.files();
for file_name in &files {
if let Some(file) = file_engine.read_file_to_string(file_name).await {
files_uploaded.write().push(file);
}
}
}
};
2023-04-25 13:16:11 +00:00
2024-01-16 19:18:46 +00:00
rsx! {
2024-02-14 20:33:07 +00:00
style { {include_str!("./assets/file_upload.css")} }
input {
r#type: "checkbox",
id: "directory-upload",
checked: enable_directory_upload,
oninput: move |evt| enable_directory_upload.set(evt.checked()),
},
label {
2024-02-14 20:33:07 +00:00
r#for: "directory-upload",
"Enable directory upload"
}
2023-04-25 13:16:11 +00:00
input {
r#type: "file",
accept: ".txt,.rs",
2023-04-25 14:26:56 +00:00
multiple: true,
2024-01-15 21:06:05 +00:00
directory: enable_directory_upload,
onchange: upload_files,
2023-04-25 13:16:11 +00:00
}
2024-02-14 20:33:07 +00:00
2023-04-27 15:21:05 +00:00
div {
2024-02-14 20:33:07 +00:00
// cheating with a little bit of JS...
"ondragover": "this.style.backgroundColor='#88FF88';",
"ondragleave": "this.style.backgroundColor='#FFFFFF';",
id: "drop-zone",
2023-04-27 15:21:05 +00:00
prevent_default: "ondrop dragover dragenter",
2024-01-15 21:06:05 +00:00
ondrop: handle_file_drop,
ondragover: move |event| event.stop_propagation(),
2023-04-27 15:21:05 +00:00
"Drop files here"
}
2023-04-25 13:16:11 +00:00
ul {
for file in files_uploaded.read().iter() {
li { "{file}" }
}
}
2024-01-14 05:12:21 +00:00
}
2023-04-25 13:16:11 +00:00
}