file_upload.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 {
  40. r#for: "directory-upload",
  41. "Enable directory upload"
  42. }
  43. input {
  44. r#type: "file",
  45. accept: ".txt,.rs",
  46. multiple: true,
  47. directory: enable_directory_upload,
  48. onchange: upload_files,
  49. }
  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. }