14

In my application I want that when a user uploads an image file then I want to show the user the image immediately before submitting the form. This is so that they can preview the image before they submit the form.

Is there any way in HTML5 that the file uploader can show the image on the client side before the actual form is submitted?

I want to allow the user to preview the image file without uploading the file to the server (so no uploading to the temp directory either), but somehow just show the image on the client side in the client browser.

Seth Battin
  • 2,811
  • 22
  • 36

2 Answers2

45

Since this was the first result for google("html5 image preview"), I thought I'd flesh out a contentful answer. I hope it's helpful.

<img id="preview" src="placeholder.png" height="100px" width="100px" />
<input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
<script type="text/javascript">      
  function previewImage(input) {
    var preview = document.getElementById('preview');
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        preview.setAttribute('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    } else {
      preview.setAttribute('src', 'placeholder.png');
    }
  }
</script>
Seth Battin
  • 2,811
  • 22
  • 36
8

It sure is possible with the HTML5 File API.

Jeremy Conley
  • 924
  • 5
  • 6