Search code examples
typescriptfileblob

How am I supposed to append a Blob/File array to formData in typescript?


This would work fine if I didn't have an ARRAY of files. But it needs to be an Array.

  let file1 = new File([""], "filename");
  let file2 = new File([""], "filename");
  let files = [file1, file2];
  let formData = new FormData();
  formData.append('files', files);

This works just fine in javascript. In typescript I get this error.

TS2345: Argument of type 'Blob[]' is not assignable to parameter of type 'string | Blob'.   Type 'Blob[]' is not assignable to type 'string'.

Is there anything I can do besides // @ts-ignore?

Also the rest api I am working with requires the formData to be a Blob/File Array so I can't change anything there.


Solution

  • You might have to do something like this:

    let file1 = new File([""], "filename");
    let file2 = new File([""], "filename");
    let files = [file1, file2];
    let formData = new FormData();
    for (let file of files){
        formData.append('files', file);
    }
    

    Will you let me know if that works?

    The reason i think that is based on the discussion here: How use formData.append for a array in typescript