rustweb-sys

How to convert a string to Blob in web_sys?


I am trying to convert a string to blob using web_sys


let json_string = json::stringify(data);
let json_jsvalue = JsValue::from_str(&json_string);

let json_blob_result = Blob::new_with_str_sequence(&json_jsvalue);
let json_blob = json_blob_result.unwrap();

It gives error:

panicked at 'called Result::unwrap() on an Err value: JsValue(TypeError: Blob constructor: Argument 1 can't be converted to a sequence.


Solution

  • As explained in MDN, to create a Blob from string you need to wrap it in array:

    let json_string = json::stringify(data);
    let json_jsvalue = JsValue::from_str(&json_string);
    let json_jsvalue_array = js_sys::Array::from_iter(std::iter::once(json_jsvalue));
    
    let json_blob_result = Blob::new_with_str_sequence(&json_jsvalue_array);
    let json_blob = json_blob_result.unwrap();