Preview Image Before Uploading Using jQuery in ASP.Net

This article will show how to show an image preview when uploading images in ASP.NET using jQuery.

The following is my jQuery script and aspx code:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title>Preview Image While Upload</title>  
  7.   
  8.     <script src="jquery-1.8.2.js" type="text/javascript"></script>  
  9.   
  10.     <script type="text/javascript">  
  11.         function ShowPreview(input) {  
  12.             if (input.files && input.files[0]) {  
  13.                 var ImageDir = new FileReader();  
  14.                 ImageDir.onload = function(e) {  
  15.                     $('#impPrev').attr('src', e.target.result);  
  16.                 }  
  17.                 ImageDir.readAsDataURL(input.files[0]);  
  18.             }  
  19.         }  
  20.     </script>  
  21.   
  22. </head>  
  23. <body>  
  24.     <form id="form1" runat="server">  
  25.     <table cellpadding="10" cellspacing="4" width="70%" align="center" style="border: Solid 10px Green;  
  26.         font-weight: bold; font-size: 16pt; background-color: Skyblue; color: Blue;">  
  27.         <tr>  
  28.             <td align="center">  
  29.                 Upload Images  
  30.             </td>  
  31.         </tr>  
  32.         <tr>  
  33.             <td>  
  34.                 Select Your File To Upload #:  
  35.                 <input type="file" name="ImageUpload" id="ImageUpload" onchange="ShowPreview(this)" />  
  36.                 <asp:Button ID="btnUpload" runat="server" Text="Upload" />  
  37.             </td>  
  38.         </tr>  
  39.         <tr>  
  40.             <td>  
  41.                 <asp:Image ID="impPrev" runat="server" Height="200px" />  
  42.             </td>  
  43.         </tr>  
  44.     </table>  
  45.     </form>  
  46. </body>  
  47. </html>  
Now run the application and select an image to upload:

upload image
                                                                              Image 1

After selecting an image you can see your image.

select your fileto upload
                                                                              Image 2