Html – Show an image preview before upload

htmlimage processingupload

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?

Best Answer

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>