Previewing image uploads with FileReader in HTML5

Comments 0

Share to social media

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:

Example JavaScript:

About the author

Michael Williamson

See Profile

Michael is a software developer who likes to try out different approaches and technologies. He hates inheritance, advocates test-driven development, and thinks that the first three Wallace and Gromit shorts are quite possibly the finest hour and a half of video ever made. He blogs at http://mike.zwobble.org.

Michael Williamson's contributions