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 9663 times – thanks for reading.

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

Michael Williamson

View all articles by Michael Williamson

Related articles

Also in Blogs

Ten Years Later

It’s hard to believe, but Simple Talk has now been going for over ten years. Thanks to brilliant pieces from our writers, hard work from the team here, and countless valuable contributions from you, our readers, we’re currently receiving one million page views a month, and sitting on a hefty 2,500 articles from over 370 … Read more

Join Simple Talk

Join over 200,000 Microsoft professionals, and get full, free access to technical articles, our twice-monthly Simple Talk newsletter, and free SQL tools.

Sign up