file_upload.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 std::sync::Arc;
  6. use dioxus::prelude::*;
  7. use dioxus::{html::HasFileData, prelude::dioxus_elements::FileEngine};
  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 read_files = move |file_engine: Arc<dyn FileEngine>| async move {
  15. let files = file_engine.files();
  16. for file_name in &files {
  17. if let Some(file) = file_engine.read_file_to_string(file_name).await {
  18. files_uploaded.write().push(file);
  19. }
  20. }
  21. };
  22. let upload_files = move |evt: FormEvent| async move {
  23. if let Some(file_engine) = evt.files() {
  24. read_files(file_engine).await;
  25. }
  26. };
  27. let handle_file_drop = move |evt: DragEvent| async move {
  28. if let Some(file_engine) = evt.files() {
  29. read_files(file_engine).await;
  30. }
  31. };
  32. rsx! {
  33. style { {include_str!("./assets/file_upload.css")} }
  34. input {
  35. r#type: "checkbox",
  36. id: "directory-upload",
  37. checked: enable_directory_upload,
  38. oninput: move |evt| enable_directory_upload.set(evt.checked()),
  39. },
  40. label { r#for: "directory-upload", "Enable directory upload" }
  41. input {
  42. r#type: "file",
  43. accept: ".txt,.rs",
  44. multiple: true,
  45. name: "textreader",
  46. directory: enable_directory_upload,
  47. onchange: upload_files,
  48. }
  49. label { r#for: "textreader", "Upload text/rust files and read them" }
  50. div {
  51. // cheating with a little bit of JS...
  52. "ondragover": "this.style.backgroundColor='#88FF88';",
  53. "ondragleave": "this.style.backgroundColor='#FFFFFF';",
  54. id: "drop-zone",
  55. // prevent_default: "ondrop dragover dragenter",
  56. ondrop: handle_file_drop,
  57. ondragover: move |event| event.stop_propagation(),
  58. "Drop files here"
  59. }
  60. ul {
  61. for file in files_uploaded.read().iter() {
  62. li { "{file}" }
  63. }
  64. }
  65. }
  66. }