RUA!
Avatar

DefectingCat/fetch_file.rs

Last active: 2 years ago

Rust fetch file with browser fetch funtion in webassembly

fetch_file.rs
use anyhow::Result;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};

/// Fetch file by browser fetch
///
/// Arguments:
///
/// - `url`: target url. support relative path.
#[wasm_bindgen]
pub async fn fetch_file(url: &str) -> Result<String, JsValue> {
    let mut opts = RequestInit::new();
    opts.method("GET");
    opts.mode(RequestMode::Cors);

    let request = Request::new_with_str_and_init(url, &opts)?;

    let window = web_sys::window().ok_or("cannot access browser window")?;
    let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;

    // `resp_value` is a `Response` object.
    assert!(resp_value.is_instance_of::<Response>());
    let resp: Response = resp_value.dyn_into()?;

    // Convert this other `Promise` into a rust `Future`.
    // let json = JsFuture::from(resp.json()?).await?;
    let text = JsFuture::from(resp.text()?).await?;
    let str: String = text.as_string().ok_or("convert result to string failed")?;
    Ok(str)
}