1

I'm using a regular HTML File Picker input form item to allow my users to select files. I'd like to show them a thumbnail of the file they selected as they will be required to select many images and it can get confusing.

Does anyone know if it's possible to display the image they selected without uploading it to the server? If so, how?

If someone can point me to a post or give me an idea of how I might do this it will be greatly appreciated.

<input type="file" name="image" accept="image/*">
capdragon
  • 14,565
  • 24
  • 107
  • 153
  • Closely related: [Can I load a local file into an html canvas element?](http://stackoverflow.com/questions/13938686/can-i-load-a-local-file-into-an-html-canvas-element/13939150#13939150) – apsillers Feb 16 '15 at 16:06

2 Answers2

4
<!-- Create an <img> element to preview the image -->
<img id="image-preview" width="320">

<!-- The <input> can go anywhere in your page or <form>. Note the "onchange" attribute -->
<input type="file" name="image" accept="image/*" onchange="handleFileChange">

Make sure the following JavaScript comes after the above <img> and <input> elements. You can put this in your .js file that is loaded at the end of the page or in a <script> element at the end of page.

// Select the preview image element
const imgElement = document.getElementById('image-preview');

function handleFileChange(e) {
    // If no file was selected, empty the preview <img>
    if(!e.target.files.length) return imgElement.src = '';

    // Set the <img>'s src to a reference URL to the selected file
    return imgElement.src = URL.createObjectURL(e.target.files.item(0))
}
Raees Iqbal
  • 2,160
  • 1
  • 18
  • 15
3

This should get you started

http://jsfiddle.net/41go76g4/

Basically you read the file in with fileAPI in javascript and set the returned blob as the dataURL for an img tag.

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

    // 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 class="thumb" 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('fileInput').addEventListener('change', handleFileSelect, false);

ref: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Andrew Walters
  • 4,763
  • 6
  • 35
  • 49