18 April 2013

Previewing image uploads with FileReader in HTML5

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:

Keep up to date with Simple-Talk

For more articles like this delivered fortnightly, sign up to the Simple-Talk newsletter

This post has been viewed 9726 times – thanks for reading.

  • Rate
    [Total: 0    Average: 0/5]
  • Share

Michael Williamson

View all articles by Michael Williamson