Advertisement
umuro

Upload - Rust/Leptos

Oct 12th, 2024
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.90 KB | None | 0 0
  1. // HTML part:
  2. // <input type="file" id="fileInput" />
  3. // <button onclick="uploadFile()">Upload</button>
  4. // <progress id="uploadProgress" value="0" max="100"></progress>
  5.  
  6. use leptos::*;
  7. use wasm_bindgen::JsCast;
  8. use web_sys::{Event, HtmlInputElement, ProgressElement, XmlHttpRequest};
  9.  
  10. #[component]
  11. pub fn FileUploader(cx: Scope) -> Element {
  12.     view! { cx,
  13.         <input id="fileInput" type="file" />
  14.         <button on:click=move |_| upload_file() >"Upload"</button>
  15.         <progress id="uploadProgress" value="0" max="100"></progress>
  16.     }
  17. }
  18.  
  19. fn upload_file() {
  20.     let window = web_sys::window().expect("no global `window` exists");
  21.     let document = window.document().expect("should have a document on window");
  22.     let file_input: HtmlInputElement = document
  23.         .get_element_by_id("fileInput")
  24.         .expect("fileInput not found")
  25.         .dyn_into::<HtmlInputElement>()
  26.         .expect("fileInput should be an HtmlInputElement");
  27.     let file = match file_input.files().and_then(|files| files.get(0)) {
  28.         Some(file) => file,
  29.         None => {
  30.             web_sys::window()
  31.                 .unwrap()
  32.                 .alert_with_message("Please select a file to upload.")
  33.                 .unwrap();
  34.             return;
  35.         }
  36.     };
  37.  
  38.     let form_data = web_sys::FormData::new().unwrap();
  39.     form_data.append_with_blob("file", &file).unwrap();
  40.  
  41.     let xhr = XmlHttpRequest::new().unwrap();
  42.     xhr.open_with_async("POST", "https://your-server-endpoint/upload", true)
  43.         .unwrap();
  44.  
  45.     let progress_element: ProgressElement = document
  46.         .get_element_by_id("uploadProgress")
  47.         .expect("uploadProgress not found")
  48.         .dyn_into::<ProgressElement>()
  49.         .expect("uploadProgress should be a ProgressElement");
  50.  
  51.     let upload_clone = xhr.upload().unwrap();
  52.     let progress_callback = Closure::wrap(Box::new(move |event: Event| {
  53.         let progress_event = event.dyn_ref::<web_sys::ProgressEvent>().unwrap();
  54.         if progress_event.length_computable() {
  55.             let percent_complete = (progress_event.loaded() as f64 / progress_event.total() as f64) * 100.0;
  56.             progress_element.set_value(percent_complete);
  57.         }
  58.     }) as Box<dyn FnMut(_)>);
  59.     upload_clone.set_onprogress(Some(progress_callback.as_ref().unchecked_ref()));
  60.     progress_callback.forget();
  61.  
  62.     let ready_state_callback = Closure::wrap(Box::new(move || {
  63.         if xhr.ready_state() == 4 {
  64.             if xhr.status() == 200 {
  65.                 log::info!("File uploaded successfully: {:?}", xhr.response_text().unwrap());
  66.             } else {
  67.                 log::error!("Error uploading file: {:?}", xhr.status_text());
  68.             }
  69.         }
  70.     }) as Box<dyn FnMut()>);
  71.     xhr.set_onreadystatechange(Some(ready_state_callback.as_ref().unchecked_ref()));
  72.     ready_state_callback.forget();
  73.  
  74.     xhr.send_with_opt_form_data(Some(&form_data)).unwrap();
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement