How to read multiple files with JavaScript FileReader API one at a time?

Sometimes, we want to read multiple files with JavaScript FileReader API one at a time.

In this article, we’ll look at how to read multiple files with JavaScript FileReader API one at a time.

How to read multiple files with JavaScript FileReader API one at a time?

To read multiple files with JavaScript FileReader API one at a time, we can map the files to promises that resolves to the file content.

For instance, we write:

<input type='file' multiple>

to add a file input that accepts multiple files.

Then we write:

const upload = async (event) => {
  const files = [...event.target.files].map(file => {
    const reader = new FileReader();
    return new Promise(resolve => {
      reader.onload = () => resolve(reader.result);
      reader.readAsText(file);
    });
  });
  const res = await Promise.all(files);
  console.log(res)
}

const input = document.querySelector('input')
input.onchange = upload

We define the upload function that takes the selected files which are stored in event.target.files and spread them to an array.

Then we call map on the array with a callback that returns a promise that reads the file into a string with reader.readAsText and resolves to the read file which is stored in reader.result.

Next, we call Promise.all with the files promise array to get the file contents.

Then we select the input with document.querySelector.

And we set input.onchange to upload.

Now when we select files with the file input, we should see the contents of each file logged.

Conclusion

To read multiple files with JavaScript FileReader API one at a time, we can map the files to promises that resolves to the file content.