Search code examples
rustwebassemblyrust-wasmweb-sys

Get parameters from web_sys::File in rust


I'm sending a FileList from JavaScript and trying to read the parameters of the specific file from the list, like the file name but I'm getting the error:method not found in Option<web_sys::File> (I'have tried different variants to call the getter methods of the File like defined in the web-sys doc but no success).

#[wasm_bindgen]
pub fn get_file_list_detail(files : web_sys::FileList) -> Option<web_sys::File> {
    let first_file = files.get(1);
    log!("Test console log from rust {:?}=",first_file.name()); //this is not working
    return first_file;
}

I added the File and FileList in Cargo.toml:

[dependencies.web-sys]
version = "0.3"
features = [
    "HtmlInputElement",
    "FileList",
    "File",
    "console"
]

Solution

  • files.get(1) returns Option<File> which could be either None or Some(File) variant. You can use match statement to match these variants and take actions accordingly.

    #[wasm_bindgen]
    pub fn get_file_list_detail(files : web_sys::FileList) -> Option<web_sys::File> {
        let first_file = files.get(1);
        match first_file {
            Some(ref file) => {
                log!("Test console log from rust {:?}=",file.name());
            },
            None => {
                log!("file is Missing")
            }
        }
        
        return first_file;
    }