a blog for those who code

Thursday 10 December 2015

How to preview Image before Uploading in HTML5

In this post we will be discussing about how to preview image before uploading it to the server using HTML5 and JavaScript. We will be using HTML5 FileReader() function to accomplish it. Using FileReader() function, user can view thumbnail of the photos directly on the client side before uploading it to the server.

Before going into the detail of how to do it, we should first know what is FileReader in HTML5. FileReader object asynchronously reads the contents of files stored on the user's computer. FileList object have all the file objects which you can use to preview the image. It has 4 options to read a file and they are readAsBinaryString, readAsText, readAsDataURL or readAsArrayBuffer.

After reading a file using any of the above methods you have methods like onloadstart, onprogress, onload, onabort, onerror and onloadend can be used to track its progress. It also has properties like error (error occured while reading the file), readyState(state of FileReader) and result (the actual file contents).

FileReader Browser Support using CanIUse


Code :

<input type="file" id="file" />
<br/><br/>
<div> 
  <img id="image" />
</div>

<script>
  document.getElementById("file").onchange = function () {
    var reader = new FileReader();
    reader.onload = function(e) {
      document.getElementById("image").src = e.target.result;
    }
    reader.readAsDataURL(this.files[0]);
}
</script>

In the above code at first we are getting the file using document.getElementById("file") and creating an onchange event on it. In the onchange event we are creating a new instance of FileReader After that we are creating an onload event of that reader where we are providing the file content to image's src attribute.

Output :
Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment