How to preview multiple images

I’m trying to make an image uploader that previews the images before being uploaded. So far I have this code that takes several images but only previews one.

<input type="file" accept="image/*" onchange="loadFile(event)" multiple>
<img id="output" width="50px"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
console.log(event.target.files);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>

My question is: how can I create an img for each image?

I’m struggling to find a way that an img will be created for each image to be uploaded so that all the images will be previewed.

You need to loop over the files and create an image for each. Something like this:

    <input type="file" accept="image/*" onchange="loadFile(event)" multiple />
    <div id="output"></div>

    <script>
      const img = (src) => `<img src=${src} width="50px"/>`;

      var loadFile = function (event) {
        var output = document.getElementById('output');
        output.innerHTML = '';

        [...event.target.files].forEach(
          (file) => (output.innerHTML += img(URL.createObjectURL(file)))
        );
      };
    </script>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.