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

如何将多个File[]类型文件转换为单个Blob?适配fetch请求

问题解决:FormData提交多文件及合并为Blob的方法

在Postman中可通过form-data格式的POST请求,将多个文件放在同一个files键下提交,但直接将File[]传入formData.append()会触发TypeScript类型错误:

No overload matches this call.
Overload 1 of 3, '(name: string, value: string | Blob): void', gave the following error.
Argument of type 'File[]' is not assignable to parameter of type 'string | Blob'.
Type 'File[]' is missing the following properties from type 'Blob': size, type, arrayBuffer, stream, text
Overload 2 of 3, '(name: string, value: string): void', gave the following error.
Argument of type 'File[]' is not assignable to parameter of type 'string'.
Overload 3 of 3, '(name: string, blobValue: Blob, filename?: string | undefined): void', gave the following error.
Argument of type 'File[]' is not assignable to parameter of type 'Blob'.ts(2769)

以下是两种解决方案:

1. 模拟Postman多文件提交(推荐)

Postman中同一个键下的多文件,本质是在form-data里重复添加相同名称的字段。直接循环文件数组,多次调用append方法即可,后端框架会自动将同名字段解析为数组:

const convertFilesToFormData = (files: File[]): FormData => {
  const formData = new FormData();
  files.forEach(file => {
    // 第三个参数可选,用于指定文件名
    formData.append("files", file, file.name);
  });
  return formData;
};

这种方式符合HTTP form-data的标准规范,无需额外处理,后端兼容性最好。

2. 合并多个文件为单个Blob(需后端配合)

如果后端要求接收单个Blob格式的合并文件,可将所有文件的二进制内容合并为一个Blob。注意:这种方式需要后端提前约定解析规则(比如分隔符、归档格式),否则无法还原原始文件。

示例代码(合并为二进制流):

// 异步合并文件为单个Blob
async function mergeFilesToSingleBlob(files: File[]): Promise<Blob> {
  // 获取所有文件的ArrayBuffer
  const fileBuffers = await Promise.all(
    files.map(file => file.arrayBuffer())
  );

  // 计算总长度并创建合并后的缓冲区
  const totalLength = fileBuffers.reduce((sum, buf) => sum + buf.byteLength, 0);
  const mergedBuffer = new Uint8Array(totalLength);

  let offset = 0;
  fileBuffers.forEach(buf => {
    mergedBuffer.set(new Uint8Array(buf), offset);
    offset += buf.byteLength;
    // 可选:添加自定义分隔符(如换行符),方便后端拆分
    // mergedBuffer.set(new Uint8Array([10]), offset);
    // offset += 1;
  });

  // 返回合并后的Blob,可根据需要修改MIME类型
  return new Blob([mergedBuffer], { type: "application/octet-stream" });
}

// 使用合并后的Blob创建FormData
const convertFilesToFormData = async (files: File[]): Promise<FormData> => {
  const formData = new FormData();
  const mergedBlob = await mergeFilesToSingleBlob(files);
  formData.append("files", mergedBlob, "merged-files.bin");
  return formData;
};

若需要更规范的归档(如ZIP),可引入第三方库(如jszip)来生成标准ZIP格式的Blob,后端直接解压即可获取原始文件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:41:05