1

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);
  }
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.