Show an image preview before upload

HtmlImage ProcessingUpload

Html Problem Overview


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?

Html Solutions


Solution 1 - Html

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>

Solution 2 - Html

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");
     }
 });

Solution 3 - Html

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>

Solution 4 - Html

For background images, make sure to use url()

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

Solution 5 - Html

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHardik SondagarView Question on Stackoverflow
Solution 1 - HtmlKamyar NazeriView Answer on Stackoverflow
Solution 2 - HtmlSatinder singhView Answer on Stackoverflow
Solution 3 - Htmlyogesh chatrolaView Answer on Stackoverflow
Solution 4 - HtmlepicgearView Answer on Stackoverflow
Solution 5 - HtmlAshish YadavView Answer on Stackoverflow