Preview Image At Client Side In JavaScript, Using File Reader

One day, I got a requirement to show Image Preview before saving it on the application. I really struggled that time to achieve it. Thus, I would like to share my knowledge regarding this.

Actually, the cross domain problem will come, when we try to set the image URL of the local system.

Code 

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2.   
  3. <head runat="server">  
  4.     <title>Image Preview</title>  
  5.     <script type="text/javascript">  
  6.         function PreviewImage(event) {  
  7.             var input = event.target;  
  8.             document.getElementById("imgPreview").src = input.value;  
  9.         }  
  10.     </script>  
  11. </head>  
  12.   
  13. <body> <input type='file' accept='image/*' onchange='PreviewImage(event)'><br> <img id='output'> <img id="imgPreview" alt="no preview available" /> </body>  
  14.   
  15. </html>   

Output


Finally, find the solution, using the FileReader class. It is used to read the content of the file at client side. Let's see how to implement it, using the onchange method of the file input.

Step 1

Initialize the object for FileReader class.

Step 2

Subscribe the onload event and implement the code, as shown below.

  1. reader.onload = function() {  
  2.     var dataURL = reader.result;  
  3.     document.getElementById("imgPreview").src = dataURL;  
  4. };   

Step 3

Call the readAsDataURL method of the FileReader class. 

  1. reader.readAsDataURL(input.files[0]);   

Note

There are three methods available to read the content of the file.

  • readAsDataURL- It reads the file content as a 'data:' URL string.
  • readAsArrayBuffer- It reads the file content ArrayBuffer.
  • readAsText- It reads the file content as a string.

We can show the image, using this method. Please feel free to comment if you have any doubts regarding this and share if you know anything about it.