dioxus/examples/file_upload.rs

75 lines
2.2 KiB
Rust
Raw Normal View History

2023-04-25 13:16:11 +00:00
#![allow(non_snake_case)]
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() {
2023-07-20 20:20:14 +00:00
dioxus_desktop::launch(App);
2023-04-25 13:16:11 +00:00
}
fn App() -> Element {
let enable_directory_upload = use_state(|| false);
let files_uploaded: &UseRef<Vec<String>> = use_ref(Vec::new);
2023-04-25 13:16:11 +00:00
cx.render(rsx! {
label {
input {
r#type: "checkbox",
checked: "{enable_directory_upload}",
oninput: move |evt| {
2023-09-01 20:38:55 +00:00
enable_directory_upload.set(evt.value().parse().unwrap());
},
},
"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,
directory: **enable_directory_upload,
2023-04-25 13:16:11 +00:00
onchange: |evt| {
to_owned![files_uploaded];
async move {
2023-09-01 20:38:55 +00:00
if let Some(file_engine) = &evt.files() {
2023-04-25 13:16:11 +00:00
let files = file_engine.files();
2023-06-05 08:47:04 +00:00
for file_name in files {
sleep(std::time::Duration::from_secs(1)).await;
files_uploaded.write().push(file_name);
2023-04-25 13:16:11 +00:00
}
}
}
},
}
2023-04-27 15:21:05 +00:00
div {
width: "100px",
height: "100px",
border: "1px solid black",
prevent_default: "ondrop dragover dragenter",
ondrop: move |evt| {
to_owned![files_uploaded];
async move {
2024-01-08 22:08:21 +00:00
if let Some(file_engine) = &evt.files() {
2023-04-27 15:21:05 +00:00
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);
}
}
}
}
},
ondragover: move |event: DragEvent| {
event.stop_propagation();
},
"Drop files here"
}
2023-04-25 13:16:11 +00:00
ul {
for file in files_uploaded.read().iter() {
li { "{file}" }
}
}
})
}