AESTHETICS
AESTHETICS

Reputation: 1049

JavaScript reading and previewing multiple images

I have found code for reading multiple images on the internet.

Here is the code:

HTML

<input id="browse" type="file" onchange="previewFiles()" multiple>

JavaScript

function previewFiles() {
  var preview = document.querySelector('#preview');
  var files   = document.querySelector('input[type=file]').files;
  function readAndPreview(file) {
    // Make sure `file.name` matches our extensions criteria
    if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
      var reader = new FileReader();

      reader.addEventListener("load", function () {
        var image = new Image();
        image.height = 100;
        image.title = file.name;
        image.src = this.result;
        preview.appendChild( image );
      }, false);

    reader.readAsDataURL(file);
    }

  }

  if (files) {
    [].forEach.call(files, readAndPreview);
  }

}

I have a problem with it, as I do not fully understand what is happening and why it does not preview/seems like it is storing multiple files.

Upvotes: 1

Views: 1853

Answers (2)

user1693593
user1693593

Reputation:

The main problem in the included code is that there is no element with the id preview (ref: var preview = document.querySelector('#preview');)

Adding this and it will work. However, you can skip FileReader as it isn't needed. Instead treat the File as a Blob (they are essentially the same) and use createObjectURL() with it - the performance and the memory footprint are significant better in case you want to display a high amount of images.

document.querySelector('#browse').onchange = function() {
  var preview = document.querySelector('#preview');
  [].forEach.call(this.files, function(file) {
    if (/image\/.*/.test(file.type)) {   // use any image format the browser can read
      var img = new Image;
      img.onload = remURL;               // to remove Object-URL after use
      img.style.height = "100px";        // use style, "width" defaults to "auto"
      img.src = (URL || webkitURL).createObjectURL(file);
      preview.appendChild(img);          // add image to preview container
    }
  });
  
  function remURL() {(URL || webkitURL).revokeObjectURL(this.src)}
};
<input id="browse" type="file" multiple>
<div id=preview></div> <!-- an element with this ID was missing -->

Upvotes: 2

Amit
Amit

Reputation: 6304

Your final lines of code:

if (files) {
   [].forEach.call(files, readAndPreview);
}

Should do nothing. It goes for each over an empty array. I think you were trying to do something like:

files.forEach(readAndPreview)

Which would actually go over all of the files in the files array and call readAndPreview for them.

Upvotes: -1

Related Questions