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. function showimagepreview(input) {
  3. if (input.files && input.files[0]) {
  4. var reader = new FileReader();
  5. reader.onload = function (e) {
  6. document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
  7. }
  8. reader.readAsDataURL(input.files[0]);
  9. }
  10. }
  11. </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.