126

In my HTML form I have input filed with type file for example :

 <input type="file" multiple>

Then I'm selecting multiple files by clicking that input button. Now I want to show preview of selected images before submitting form . How to do that in HTML 5?

1

5 Answers 5

285

Here's a quick example that makes use of the URL.createObjectURL to render a thumbnail by setting the src attribute of an image tag to a object URL:

The html code:

<input accept="image/*" type="file" id="files" />
<img id="image" />

The JavaScript code:

document.getElementById('files').onchange = function () {
  var src = URL.createObjectURL(this.files[0])
  document.getElementById('image').src = src
}

The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:

function handleFileSelect (evt) {
  // Loop through the FileList and render image files as thumbnails.
  for (const file of evt.target.files) {
 
    // Render thumbnail.
    const span = document.createElement('span')
    const src = URL.createObjectURL(file)
    span.innerHTML = 
      `<img style="height: 75px; border: 1px solid #000; margin: 5px"` + 
      `src="${src}" title="${escape(file.name)}">`

    document.getElementById('list').insertBefore(span, null)
  }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>

9
  • 3
    Now How to cancel some of images for uploading and then to submit the form ? It'll really helpful to me. Commented Dec 28, 2012 at 12:32
  • But I want to know that how to delete particular file to prevent it from uploading. It's define in some structure. Commented Dec 28, 2012 at 16:06
  • 5
    Simply disable the file input element, and it won't be uploaded! So in the example above: document.getElementById("uploadImage").disabled = true Commented Dec 28, 2012 at 16:13
  • @KamyarNazeri If FileReader is not availabel, then how about it ? Commented Nov 19, 2013 at 1:18
  • 1
    @Nicholas The code snippet under "Show snippet section" actually lets you load multiple images and preview them all Commented Jun 11, 2016 at 15:51
22

Here I did with jQuery using FileReader API.

Html Markup:

<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>

jQuery:

Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message

$("#fileUpload").on('change', function () {
 
     //Get count of selected files
     var countFiles = $(this)[0].files.length;
 
     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();
 
     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {
 
             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {
 
                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }
 
                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }
 
         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });
3
  • 1
    isnt consider bad practise if you declear var in for loop ? everytime for loop iterate new variable reader will be declear..
    – Phoenix
    Commented Jun 26, 2016 at 14:50
  • Adding accept="image/*" attribute to the <input> can help in preventing non-image file types from being selected.
    – August
    Commented Apr 19, 2019 at 1:45
  • How can I show the names of the images along with the image preview?
    – Naveenbos
    Commented Feb 14, 2020 at 16:49
4

function handleFileSelect(evt) {
    var files = evt.target.files;

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = 
          [
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', 
            e.target.result,
            '" title="', escape(theFile.name), 
            '"/>'
          ].join('');
          
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />
<output id="list"></output>

2

For background images, make sure to use url()

node.backgroundImage = 'url(' + e.target.result + ')';
2

Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

Don't forget to validate image extension.

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files = e.target.files;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);
      image_preview.appendChild(image);
  }
}

file_input.addEventListener('change', handle_file_preview);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.