Showing Preview of an Image Without Postback in ASP.Net

Clients often want to store the image of users but before uploading the image of a user to the server or in a database, the client needs to allow the user to preview his/her photo.

There is very simple solution for this using JavaScript by which your page will not do a postback and the user can preview his/her photo. Let us demonstrate the preceding explanation practically by creating one simple web site as follows.

Add a new "Website" named "Website1".



And you will get the default page named "Default.aspx".



Add a File upload control named "FileUpload1" and an image control of HTML named "img" to the page.



Add a JavaScript function named "showimagepreview()" in the <script> tag as in the following:

  1. <script type="text/javascript">  
  2.   
  3.         function showimagepreview(input) {  
  4.   
  5.             if (input.files && input.files[0]) {  
  6.                 var reader = new FileReader();  
  7.                 reader.onload = function (e) {  
  8.   
  9.                     document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);                     
  10.                 }  
  11.                 reader.readAsDataURL(input.files[0]);  
  12.             }  
  13.         }  
  14.   
  15.     </script>  


Now I will call this function on the event named "onchange()" on the fileupload control with a parameter "this".

Note: Here the "this" parameter is the upload control itself.
  1. onchange="showimagepreview(this)"  


Now I will run the page that will look like:



I will select the image and here is the output.

 

Up Next
    Ebook Download
    View all
    Learn
    View all