You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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);
}

原理说明

  1. 发送端:用FileReader.readAsDataURL()将Blob转换为包含Base64编码的字符串,提取编码部分后通过消息发送。
  2. 接收端:将Base64字符串解码为Uint8Array(二进制数组),再用该数组生成Blob,此时的Blob与原始Blob完全一致,能正常生成可用的URL。

内容的提问来源于stack exchange,提问作者m.a.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:25:29