如何在web_sys中将字符串转为Blob?遇构造函数参数类型错误
解决web_sys中字符串转Blob的类型错误
报错原因
Blob::new_with_str_sequence要求传入字符串序列(如字符串数组),但你直接传入了单个字符串的JsValue,不符合参数类型要求,触发TypeError。
修正方案
方案一:显式创建JS数组并指定MIME类型
use wasm_bindgen::JsValue; use web_sys::Blob; use js_sys::Array; // 序列化数据为JSON字符串 let json_string = json::stringify(data); // 创建包含目标字符串的JS数组 let content_array = Array::new(); content_array.push(&JsValue::from_str(&json_string)); // 配置Blob的MIME类型为application/json let blob_options = Blob::new_with_blob_init_dict( &JsValue::from_serde(&serde_json::json!({"type": "application/json"})).unwrap() ); // 创建Blob实例 let json_blob = Blob::new_with_sequence_and_options(&content_array, &blob_options).unwrap();
方案二:直接序列化字符串数组为JsValue
let json_string = json::stringify(data); // 将单个字符串包装成数组,再转为JsValue let str_sequence = JsValue::from_serde(&vec![&json_string]).unwrap(); // 创建Blob实例 let json_blob = Blob::new_with_str_sequence(&str_sequence).unwrap();
核心要点
- Blob构造函数的第一个参数必须是可迭代的序列类型,哪怕只有一段内容,也要放入数组中。
- 指定
application/json类型能让Blob被系统正确识别为JSON格式,推荐添加。
内容的提问来源于stack exchange,提问作者Amiya Behera
相关产品推荐
相关产品推荐

