Click here to monitor SSC

Simple-Talk developer. Yes, it's probably my fault.

Previewing image uploads with FileReader in HTML5

Published 18 April 2013 12:57 pm

If a user is filling out an HTML form, and that form happens to include an image upload, it would be nice to show them a preview of the image. Using FileReader in HTML5, this turns out to be reasonably straightforward. The code below looks for any file input element with the class upload-image, and inserts an <img> element just before it. Whenever the user selects a file, it uses a FileReader to grab the data URI for the selected image, and sets the src attribute on the <img>.

As an added bonus, if the file input element has a data-placeholder attribute, it will use the value of the attribute to set the source of the image element when no file has been selected. One use case might be if you're providing a form to allow an update to an existing item. By setting the placeholder to the current image for that item, you indicate to the user that uploading no file keeps the current image. Then, on the server-side, don't update the image if the user hasn't uploaded a file.

Example HTML:
<input type="file" name="photo" class="upload-image"
    data-placeholder="/uploads/images/hat.jpg" />
Example JavaScript:
Array.prototype.forEach.call(
    document.getElementsByClassName("upload-image"),
    function(fileElement) {
        var previewElement = document.createElement("img");
        previewElement.style.display = "block";
        fileElement.parentNode.insertBefore(previewElement, fileElement);
        
        var fileReader = new FileReader();
        
        fileReader.onload = function(event) {
            previewElement.src = event.target.result;
        };
        
        fileElement.addEventListener("change", updateImagePreview, false);
        updateImagePreview();
        
        function updateImagePreview() {
            var file = fileElement.files[0];
            if (file) {
                fileReader.readAsDataURL(file);
            } else {
                var placeholderSrc = fileElement.getAttribute("data-placeholder");
                if (placeholderSrc) {
                    previewElement.src = placeholderSrc;
                } else {
                    previewElement.removeAttribute("src");
                }
            }
        }
    }
);

2 Responses to “Previewing image uploads with FileReader in HTML5”

  1. drmcclelland says:

    Another approach I’ve used (which has a fallback for browsers that don’t support HTML5′s FileReader – like older Internet Explorer versions):

    function readURL(imgFile) {

    var preview = document.getElementById("preview");

    // Check for HTML5 FileReader support
    if (window.FileReader) {
    var f = imgFile.files[0];

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

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function (theFile) {
    return function (e) {
    // Render thumbnail.
    var span = document.getElementById("preview_span");
    if (span == null) {
    span = document.createElement("span");
    span.id = "preview_span";
    }
    span.innerHTML = [''].join('');
    preview.insertBefore(span, null);
    };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
    } else {
    // No FileReader support, assuming older IE version.
    preview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='" + imgFile.value + "')";
    preview.style.width = "200px";
    preview.style.height = "200px";
    }
    }

    This also allows you to let the user repeatedly browser for a different image and displays it instead of the previously-previewed image.

  2. aasaif2000 says:

    What will be the HTML of the above code which works in prior IE10 versions.

Leave a Reply