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

heic2any返回Blob|Blob[]类型与FileReader.readAsDataURL参数不兼容问题

HEIC转码后上传GCS时FileReader类型不匹配报错

执行代码

const heicReader = new FileReader();

heicReader.onload = async () => {
  const heicImageString = heicReader.result;

  const { download_url } = await uploadPhotoToGcs({
    base64: heicImageString,
    type: 'image/png',
  });
  this.onSubmitImageMessage(download_url);
};

const blobUrl = URL.createObjectURL(imageData);
const blobRes = await fetch(blobUrl);
const imgBlob = await blobRes.blob();
const convertedFile = await heic2any({ blob: imgBlob });

heicReader.readAsDataURL(convertedFile);
return;

报错信息

const convertedFile: Blob | Blob[]
Argument of type 'Blob | Blob[]' is not assignable to parameter of type 'Blob'.
  Type 'Blob[]' is missing the following properties from type 'Blob': size, type, arrayBuffer, stream, text

问题关键点及解决方法

你忽略了heic2any的返回值特性:它处理HEIC文件时,如果原文件包含多张图片(比如苹果的Live Photo),会返回Blob数组;单张图片则返回单个Blob。而FileReader.readAsDataURL()只接受单个Blob类型参数,所以当返回数组时就会触发类型不匹配错误。

根据业务需求,有两种处理方式:

  1. 仅处理第一张图片:如果只需要上传单张图片,直接取数组的第一个元素
// 修改convertedFile的处理逻辑
const targetBlob = Array.isArray(convertedFile) ? convertedFile[0] : convertedFile;
heicReader.readAsDataURL(targetBlob);
  1. 处理所有图片:如果需要上传所有图片,遍历数组逐个处理
// 遍历所有转换后的Blob
for (const blob of (Array.isArray(convertedFile) ? convertedFile : [convertedFile])) {
  const reader = new FileReader();
  reader.onload = async () => {
    const { download_url } = await uploadPhotoToGcs({
      base64: reader.result,
      type: 'image/png',
    });
    this.onSubmitImageMessage(download_url);
  };
  reader.readAsDataURL(blob);
}

内容的提问来源于stack exchange,提问作者Shamoon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:25:34