1
0

file_upload.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //! This example shows how to use the `file` methods on FormEvent and DragEvent to handle file uploads and drops.
  2. //!
  3. //! Dioxus intercepts these events and provides a Rusty interface to the file data. Since we want this interface to
  4. //! be crossplatform,
  5. use dioxus::html::HasFileData;
  6. use dioxus::prelude::*;
  7. use tokio::time::sleep;
  8. fn main() {
  9. launch(app);
  10. }
  11. fn app() -> Element {
  12. let mut enable_directory_upload = use_signal(|| false);
  13. let mut files_uploaded = use_signal(|| Vec::new() as Vec<String>);
  14. let upload_files = move |evt: FormEvent| async move {
  15. for file_name in evt.files().unwrap().files() {
  16. // no files on form inputs?
  17. sleep(std::time::Duration::from_secs(1)).await;
  18. files_uploaded.write().push(file_name);
  19. }
  20. };
  21. let handle_file_drop = move |evt: DragEvent| async move {
  22. if let Some(file_engine) = &evt.files() {
  23. let files = file_engine.files();
  24. for file_name in &files {
  25. if let Some(file) = file_engine.read_file_to_string(file_name).await {
  26. files_uploaded.write().push(file);
  27. }
  28. }
  29. }
  30. };
  31. rsx! {
  32. style { {include_str!("./assets/file_upload.css")} }
  33. input {
  34. r#type: "checkbox",
  35. id: "directory-upload",
  36. checked: enable_directory_upload,
  37. oninput: move |evt| enable_directory_upload.set(evt.checked()),
  38. },
  39. label { r#for: "directory-upload", "Enable directory upload" }
  40. input {
  41. r#type: "file",
  42. accept: ".txt,.rs",
  43. multiple: true,
  44. directory: enable_directory_upload,
  45. onchange: upload_files,
  46. }
  47. div {
  48. // cheating with a little bit of JS...
  49. "ondragover": "this.style.backgroundColor='#88FF88';",
  50. "ondragleave": "this.style.backgroundColor='#FFFFFF';",
  51. id: "drop-zone",
  52. prevent_default: "ondrop dragover dragenter",
  53. ondrop: handle_file_drop,
  54. ondragover: move |event| event.stop_propagation(),
  55. "Drop files here"
  56. }
  57. ul {
  58. for file in files_uploaded.read().iter() {
  59. li { "{file}" }
  60. }
  61. }
  62. }
  63. }