DoneDeal0
DoneDeal0

Reputation: 6257

How to append multiple files input to formData?

I have a basic multiple files input. When selecting one or several images, I trigger an uploadImages function. This function returns an error because it seems I can't loop over my files to append them to a formData:

error TypeError: files.forEach is not a function

Where is the mistake here?

<input
        type="file"
        accept="image/png, image/jpeg"
        placeholder="upload"
        multiple
        onChange={(e) => uploadImages(e.target.files, 3)}
      />
      
export async function uploadImages(files, userid) {
  try {
    const images = new FormData();
    if (files && files.length > 0) {
      files.forEach((file) => images.append("image", file));
    }
    const res = await ax.post(
      process.env.SERVER_URL + "/upload-images",
      images,
      userid
    );
    return console.log("success", res);
  } catch (err) {
    console.log("error", err);
  }
}

Upvotes: 1

Views: 600

Answers (1)

D. Pardal
D. Pardal

Reputation: 6587

For now, HTMLInputElement.files returns a FileList instead of an Array. This means that you can't use array methods on it. In the future, this might be changed to extend an Array.

You can use

files = [...files]

at the start of your function to convert the FileList to an Array.

Upvotes: 2

Related Questions