Categories
JavaScript Answers

How to add a multiple files input and use file reader to preview the selected files with JavaScript?

Spread the love

Sometimes, we want to add a multiple files input and use file reader to preview the selected files with JavaScript.

In this article, we’ll look at how to add a multiple files input and use file reader to preview the selected files with JavaScript.

How to add a multiple files input and use file reader to preview the selected files with JavaScript?

To add a multiple files input and use file reader to preview the selected files with JavaScript, we can loop through each selected file, read them into a data URL, create an image and set the src attribute to the URL, and then append the img element to the DOM.

For instance, we write:

<input type='file' multiple>
<div>

</div>

to add an file input and a div.

Then we write:

const input = document.querySelector('input[type="file"]')
const div = document.querySelector('div')
const picReader = new FileReader();

input.onchange = async (e) => {
  for (const file of e.target.files) {
    await new Promise(resolve => {
      picReader.onload = (e) => {
        const img = new Image()
        img.src = e.target.result
        img.width = 100
        div.appendChild(img)
        resolve()
      }
      picReader.readAsDataURL(file);
    })
  }
}

to select both elements with querySelector.

Then we set the input.onchange property to a function that loops through each selected file with the for-of loop.

In the loop, we create a promise with a callback that sets the picReader.onload property to a funxction that creates a new img element with new Image().

Then we set the src to the data URL that we get from reading the file with:

img.src = e.target.result

And then we call div.appendChild with img to add the img element as the child of the div.

Next, we call resolve to resolve the promise.

Then we call readAsDataURL with file to read the file.

As a result, when we select one or more image files, we can see the selected images on the page.

Conclusion

To add a multiple files input and use file reader to preview the selected files with JavaScript, we can loop through each selected file, read them into a data URL, create an image and set the src attribute to the URL, and then append the img element to the DOM.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *