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:
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Preview Image While Upload</title>
-
- <script src="jquery-1.8.2.js" type="text/javascript"></script>
-
- <script type="text/javascript">
- function ShowPreview(input) {
- if (input.files && input.files[0]) {
- var ImageDir = new FileReader();
- ImageDir.onload = function(e) {
- $('#impPrev').attr('src', e.target.result);
- }
- ImageDir.readAsDataURL(input.files[0]);
- }
- }
- </script>
-
- </head>
- <body>
- <form id="form1" runat="server">
- <table cellpadding="10" cellspacing="4" width="70%" align="center" style="border: Solid 10px Green;
- font-weight: bold; font-size: 16pt; background-color: Skyblue; color: Blue;">
- <tr>
- <td align="center">
- Upload Images
- </td>
- </tr>
- <tr>
- <td>
- Select Your File To Upload #:
- <input type="file" name="ImageUpload" id="ImageUpload" onchange="ShowPreview(this)" />
- <asp:Button ID="btnUpload" runat="server" Text="Upload" />
- </td>
- </tr>
- <tr>
- <td>
- <asp:Image ID="impPrev" runat="server" Height="200px" />
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
Now run the application and select an image to upload:
Image 1
After selecting an image you can see your image.
Image 2