1

How can I send multiple file to the server using below HTML elements:

<input name="file1" type="file" />
<input name="file2" type="file" /> 
<input name="file3" type="file" /> 

Knowing that, using <input type="file" multiple /> element data can be sent as:

const formData = new FormData();
const photos = document.querySelector('input[type="file"][multiple]');

formData.append('title', 'My Vegas Vacation');
for (let i = 0; i < photos.files.length; i++) {
  formData.append('photos', photos.files[i]);
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData,
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
  • The answer depends on your server. The code you have now will add multiple `photos` parameters, one for each file. If you are using `multer`, you can use the `array` method to handle them all: https://stackoverflow.com/questions/35192841/fetch-post-with-multipart-form-data – rfestag Aug 08 '20 at 20:23

1 Answers1

0

You can append all the files from the inputs in much the same manner by looping over each element.

const formData = new FormData();
/*more specific selector: 
  "input[type=file][name=file1],input[type=file][name=file2],input[type=file][name=file3]"*/
document.querySelectorAll("input[type=file]").forEach(
    input=>formData.append('photos',input.files[0]);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80