Chrome消息传递中Blob处理问题:blob.text()还原后文件损坏
修复Blob通过Chrome Message API传递后的损坏问题
问题核心在于你用blob.text()处理二进制Blob(比如图片),这会导致数据损坏。因为text()是将Blob按UTF-8编码解码为字符串,而图片这类非文本二进制数据包含大量不符合UTF-8规范的字节,解码时会丢失或篡改原始数据,最终无法正确还原Blob。
正确解决方案:用Base64编码传递二进制数据
Base64是专门用于将二进制数据转换为文本的编码方式,能完整保留原始信息,适合通过Message API传递。
发送端(Chrome扩展)代码修改:
fetch(request.url) .then(r => r.blob()) .then(blob => { const filetype = blob.type; const reader = new FileReader(); reader.onload = () => { // 从DataURL中提取Base64编码部分 const base64Data = reader.result.split(',')[1]; const message = { blobBase64: base64Data, url: request.url, filetype: filetype }; // 本地验证还原的Blob const decodedData = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0)); const new_blob = new Blob([decodedData], { type: filetype }); console.log(URL.createObjectURL(blob)); console.log(URL.createObjectURL(new_blob)); sendResponse(message); }; // 将Blob读取为DataURL(包含Base64编码) reader.readAsDataURL(blob); });
接收端(Web应用)代码:
// 处理收到的消息 function handleReceivedMessage(message) { // 解码Base64为Uint8Array const decodedData = Uint8Array.from(atob(message.blobBase64), char => char.charCodeAt(0)); // 还原Blob const restoredBlob = new Blob([decodedData], { type: message.filetype }); // 示例:生成URL并显示图片 const imgUrl = URL.createObjectURL(restoredBlob); const imgElement = document.createElement('img'); imgElement.src = imgUrl; document.body.appendChild(imgElement); }
原理说明
- 发送端:用
FileReader.readAsDataURL()将Blob转换为包含Base64编码的字符串,提取编码部分后通过消息发送。 - 接收端:将Base64字符串解码为
Uint8Array(二进制数组),再用该数组生成Blob,此时的Blob与原始Blob完全一致,能正常生成可用的URL。
内容的提问来源于stack exchange,提问作者m.a.
相关产品推荐
相关产品推荐

