javascripttypescriptfileblobfetch-api

How to convert multiple Files (as File[]) into a single Blob?


In Postman, it is possible to initiate a POST request with a body of form-data and the below key-value pairs:

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


However, when I tried putting multiple files, as File[] into a single Blob (as the below sample shows):

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

It return the below error:

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)

I would like to know if it is possible and the methods to convert to Blob type for later fetch requests.


Solution

  • formData.append() does not accepts File[], see FormData/append#value

    This can be a string or Blob (including subclasses such as File)

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

    TS Playground