Skip to content

FormData append multiple files | JavaScript

  • by

You need to add the multiple properties to the <input> element to FormData appends multiple files in JavaScript. Only then you’ll be able to select multiple files from your drive.

<input type="file" id="fileInput" multiple />

Next, accept an array of files as an argument and simply loop through the array and append the files to the FormData object:

const uploadFile = (files) => {
  console.log("Uploading file...");
  const API_ENDPOINT = "https://file.io";
  const request = new XMLHttpRequest();
  const formData = new FormData();

  request.open("POST", API_ENDPOINT, true);
  request.onreadystatechange = () => {
    if (request.readyState === 4 && request.status === 200) {
      console.log(request.responseText);
    }
  };
  
  for (let i = 0; i < files.length; i++) {
    formData.append(files[i].name, files[i])
  }
  request.send(formData);
};

Finally, call the method with an array of files as an argument:

fileInput.addEventListener("change", event => {
  const files = event.target.files;
  uploadFile(files);
});

Source: freecodecamp.org/news/formdata-explained/

FormData append multiple files

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <div id="app"></div>

  <script>
   document.getElementById("app").innerHTML = `
   <h1>File Upload & FormData Example</h1>
   <div>
   <input type="file" id="fileInput" multiple />
   </div>
   `;

   const fileInput = document.querySelector("#fileInput");

   const uploadFile = (files) => {
    console.log("Uploading file...");
    const API_ENDPOINT = "https://file.io";
    const request = new XMLHttpRequest();
    const formData = new FormData();

    request.open("POST", API_ENDPOINT, true);
    request.onreadystatechange = () => {
      if (request.readyState === 4 && request.status === 200) {
        console.log(request.responseText);
      }
    };
    
    for (let i = 0; i < files.length; i++) {
      formData.append(files[i].name, files[i])
    }
    request.send(formData);
  };

  fileInput.addEventListener("change", event => {
    const files = event.target.files;
    uploadFile(files);
  });
</script>

</body>
</html>

Output:

FormData append multiple files

Do comment if you have any doubts or suggestions on this Js FormData topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading