How To Upload Multiple Files At Once Using JavaScript

file uploader

In this resource-rich world we live in, uploading a single file at a time will take you back in decades. This is especially true if your work revolves a lot around uploading multiple items such as image files, video files, etc. This article will take you through how to upload multiple files at once using JavaScript. However, if you need a quick and secure way, you can always go for other options like a java file upload API or try some of the best file upload sites of 2022.

Method For Utilizing JavaScript To Manage Multiple File Uploads

You can use JavaScript to create a File upload feature that allows users to upload multiple files to the server. These multiple files can range from an image, zip file, or video. However, your file uploader should be able to send metadata along with the file. This metadata is necessary to do various processes about files. But, the good news is, JavaScript also makes sending metadata easy.

Furthermore, there are several approaches you can use to manage multiple file uploads in JavaScript, for example, using a File Uploader and API. They allow you to read the contents of a file as a data URL, which you can then use to display the file or send it to a server via an HTTP request.

Also, note that file uploading can be implemented in other ways like using a PHP function as well.

The Basic Components

how to upload multiple files at once

We will be demonstrating how to upload multiple files by building a simple uploader app. This uploader should contain a form with a submit button and a file input. This poses a medium for users to upload. And, there should be roughly 41 lines of code in the final app.

Multiple Attributes

Let’s start off by creating the form. If you are unfamiliar with HTML, you can use a guide to HTML image uploader to get an idea of uploading multiple images.

The first thing we must make sure to do after creating a simple form is to set the multiple properties to the file input. This will let the browser know that using the input box, you can select multiple files simultaneously.

<form id='file-catcher'>
<input id='file-input' type='file' multiple/>
<button type='submit'>
Submit
</button>
</form>

Keeping An Eye Out For Changes And Downloading All Those Files

Now that a form is up and ready to accept files, you have to do some quality assurance. The file input should know when there is a change, a.k.a a new file input. Since we are dealing with multiple files here, there should be an array to store all the files as well. The JavaScript code below well demonstrates that:

var fileInput = document.getElementById('file-input');
var fileList = [];

fileInput.addEventListener('change', function (evnt) { 

     fileList = [];
    for (var i = 0; i < fileInput.files.length; i++) {
        fileList.push(fileInput.files[i]);
    }
  }

);

Capturing The Attached Document Event

Next, you will need to add an event listener to the form that listens for the submit event. This event will be triggered when the user clicks the submit button on the form. The following code does that:

var fileCatcher = document.getElementById('file-catcher');

fileCatcher.addEventListener('submit', function (evnt) {
  evnt.preventDefault();
  fileList.forEach(function (file) {
      sendFile(file);
    });
  }

);

Do note that the id, “file-catcher”, here references the HTML id with the form tag.

FormData and Ajax

Now, we have a form that accepts forms and a JavaScript code that listens to changes in file inputs. Using this, we can implement a quick and easy file upload using Ajax like the one below that sends the files to a server.

sendFile = function (file) {
  var formData = new FormData();
  var request = new XMLHttpRequest();

  formData.set('file', file);
  request.open("POST", 'https://server.endpoint.to/send/files/to');
   request.send(formData);
};

Here, the FormData method is used to create an instance for our file. Then, the XMLHttpRequest() is created to transmit the formData instance.

Serial Chunk Vs. Parallel Streams

In JavaScript, a serial chunk is a group of synchronous tasks that are executed one after the other, in a sequential manner. This means that each task must wait for the previous task to complete before it can start.

On the other hand, parallel streams are asynchronous tasks that can be executed concurrently. This means that multiple tasks can be performed at the same time, without having to wait for each other to complete them.

Here is an example of a serial chunk in JavaScript:

const tasks = [task1, task2, task3];

for (const task of tasks) {
  task();
}

In this example, task1 will be executed first, followed by task2, and then task3. Each task will be executed in a sequential manner, and the next task will not start until the previous one has been completed.

Here is an example of parallel streams in JavaScript:

const tasks = [task1, task2, task3];

Promise.all(tasks).then(() => {
  console.log('All tasks have completed');
});

In this example, task1, task2, and task3 will all be executed concurrently, without having to wait for each other to complete. Once all tasks have been completed, the then callback function will be called.

It is important to note that parallel streams are generally more efficient than serial chunks, as they can take advantage of multiple processors or cores to execute tasks simultaneously. However, they can also be more complex to implement and may require the use of additional libraries or APIs, such as the Promise object in the example above.

parallel streaming

As you might have already guessed, uploading multiple files make use of parallel streaming.

 

Final or Next Step

We kept our “how to upload multiple files at once” example intentionally straightforward to highlight the crucial elements of the form submission. As a result of it, we have avoided talking about the following points.

  1. We didn’t validate the form submission to verify that the chosen files have actually been selected
  2. Our process didn’t handle request responses to inform the user if the files uploaded were successful or not

So as the next step you have to implement the above feature in your file upload code. However, there is an easy way to do all these. That’s by using the API from Filestack.

 

Upload Multiple Files With Filestack’s API

how to upload multiple files at once

Filestack’s API has revolutionized the way users can upload multiple files with ease and is considered the best free file uploader. Utilizing the power of their simple yet comprehensive Dynamic Delivery Network, users are able to drag and drop hundreds of files and quickly store them in one central location. Additionally, Filestack provides a free SDK toolkit for developers that allows them to integrate the technology into their applications with ease.

From simple document uploads to complex media assets, Filestack’s modern API makes it easier than ever before to unlock maximum value from your assets!

Filestack How to upload multiple Files

Compete Overview Of Upload Multiple Files Using Javascript With Example

The following is the complete code for a form that accepts multiple files to upload into an Ajax server:

(function () { //defining filecatcher var fileCatcher = document.getElementById(‘file-catcher’); //defining fileinput var fileInput = document.getElementById(‘file-input’); //defining File list display var fileListDisplay = document.getElementById(‘file-list-display’); //declaring file list var fileList = []; var renderFileList, sendFile; fileCatcher.addEventListener(‘submit’, function (evnt) {
  evnt.preventDefault();
    fileList.forEach(function (file) {
    sendFile(file);
    });
  });
 
  fileInput.addEventListener(‘change’, function (evnt) {
fileList = [];
  for (var i = 0; i < fileInput.files.length; i++) {
    fileList.push(fileInput.files[i]);
    }
    renderFileList();
  });
 
  renderFileList = function () {
  fileListDisplay.innerHTML = ;
    fileList.forEach(function (file, index) {
    var fileDisplayEl = document.createElement(‘p’);
      fileDisplayEl.innerHTML = (index + 1) + ‘: ‘ + file.name;
      fileListDisplay.appendChild(fileDisplayEl);
    });
  };
 
  sendFile = function (file) {
  var formData = new FormData();
    var request = new XMLHttpRequest();

    formData.set(‘file’, file);
    request.open(“POST”, ‘https://jsonplaceholder.typicode.com/photos’);
    request.send(formData);
  };
})();

Conclusion

How to upload multiple files at once using JavaScript is a simple process. You can do it by using an HTML form with a file input field that allows the selection of multiple files. Then you need to add a JavaScript event listener to the form to handle the file upload process when the form is submitted. Finally, access the list of selected files using the files property of the file input field, and send the files to a server using an HTTP request. There are also several libraries and APIs available for you that can make the implementation of multiple file uploads even easier.

Want to try a file upload API for free? Try Filestack’s File Upload API today!

FAQ 

Can I upload multiple files at once?

Yes, it is possible to upload multiple files at once. This can be done using an HTML form with a file input field that allows the selection of multiple files, and a server-side script to handle the file upload process.

How do I select multiple files to upload at once?

To select multiple files to upload at once, you can use an HTML form with a file input field that has multiple attributes set to true. This will allow the user to select multiple files using the file picker or by dragging and dropping files into the designated area.

How do I send the selected files to the server?

To send the selected files to the server, you can use an HTTP request such as a POST request with the files as form data. You can use a server-side script or a third-party library to handle the file upload process on the server.

Are there any tools or libraries available to make uploading multiple files easier?

Yes, there are several tools and libraries available that can make uploading multiple files easier such as the Filestack File Upload API.

Read More →