如何将多个文件(如 File[])转换为单个 Blob?

问题描述 投票:0回答:1

在 Postman 中,可以发起一个

POST
请求,其正文为
form-data
和以下
key-value
对:

Screenshot of Postman multi-files inside a single key-value pair


但是,当我尝试将多个文件,如

File[]
放入单个
Blob
中时(如下例所示):

const convertFilesToFormData = (files: File[]): FormData => {
  let formData = new FormData();
  formData.append("files", files);
  return formData;
} // REMARK: A simplified function of what I have.

它返回以下错误:

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)

我想知道是否可以以及转换为

Blob
类型以供以后
fetch
请求的方法。

javascript typescript file blob fetch-api
1个回答
0
投票

formData.append()
不接受
File[]
,请参阅FormData/append#value

这可以是

string
Blob
(包括子类,例如
File

const convertFilesToFormData = (files: File[]): FormData => {
  let formData = new FormData();
  for (const file of files) {
    formData.append("files", file);
  }
  return formData;
}

TS游乐场

© www.soinside.com 2019 - 2024. All rights reserved.