Show Image Preview Before Uploading To Database Using jQuery In ASP.NET

Introduction

In this blog, we will discuss how to show an image preview before uploading to a database in ASP.NET. We will save the image path in the database and the image in the images folder of our project. This form has all textbox, dropdown list, and file upload controller validation.

Step 1

Create a database in the MS SQL Server of your choice.

  1. CREATE TABLE [dbo].[Employee](    
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,    
  3.     [First_Name] [nvarchar](50) NULL,    
  4.     [Last_name] [nvarchar](50) NULL,    
  5.     [Gender] [char](10) NULL,    
  6.     [DateofBirth] [nvarchar](50) NULL,    
  7.     [Phone_Number] [nvarchar](50) NULL,    
  8.     [Email] [nvarchar](50) NULL,    
  9.     [Image] [nvarchar](50) NULL,    
  10.     [Created] [datetime] NULL,    
  11.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED     
  12. (    
  13.     [ID] ASC    
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  15. ON [PRIMARY]    
  16.     
  17.     
  18. Create procedure [dbo].[spAddNewlEmplyee]    
  19. (    
  20. @First_Name nvarchar(50),    
  21. @Last_Name nvarchar(50),    
  22. @Gender char(10),    
  23. @DateofBirth nvarchar(50),    
  24. @Phone_Number nvarchar(50),    
  25. @Email nvarchar(50),    
  26. @Image nvarchar(50),    
  27. @Created nvarchar(50)    
  28. )    
  29. as    
  30. begin    
  31. insert into Employee(First_Name,Last_Name,Gender,DateofBirth,Phone_Number,Email,Image,Created)    
  32. values(@First_Name,@Last_Name,@Gender,@DateofBirth,@Phone_Number,@Email,@Image,GETDATE())    
  33. end    
  34.     
  35. Create procedure [dbo].[spGetAllEmplyee]    
  36. as    
  37. begin    
  38. selectfrom Employee    
  39. end     

Step 2

Create a web project with an empty template, give it a meaningful name. Right-click and add a new item, choose a web form and give it a name. Open web.config file to add a connection to your project.

  1. <connectionStrings>  
  2.   <add name="DBCS" connectionString="data source=FARHAN\SQLEXPRESS; database=EmployeeDB; Integrated Security=true;" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  

Step 3

Add a validation setting for validation control in the webconfig file of your project.

  1. <appSettings>  
  2.       <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />  
  3. </appSettings>  

Step 4

Add the script and style CDN links in the head section.

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">  
  3. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
  4. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>  
  5. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
  6. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  

Step 5

Write a function for image preview in jQuery.

  1. <script type="text/javascript">  
  2.         //Image Upload Preview  
  3.         function ShowImagePreview(input) {  
  4.             if (input.files && input.files[0]) {  
  5.                 var reader = new FileReader();  
  6.                 reader.onload = function (e) {  
  7.                     $('#imagePreview').prop('src', e.target.result);  
  8.                 };  
  9.                 reader.readAsDataURL(input.files[0]);  
  10.             }  
  11.         }  
  12. //Date of Birth datepicker  
  13.         $(document).ready(function () {         
  14.             $('#txtDateofBirth').datepicker({  
  15.                 changeMonth: true,  
  16.                 changeYear: true,  
  17.                 dateFormat: "dd-mm-yy",  
  18.                 yearRange: "-100:+10"  
  19.             });  
  20.         });  
  21.     </script>  

Step 6

Design the HTML as given below.

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.         <div class="container">  
  4.             <h3 class="text-center">Show Image Preview Before Uploading to Database in ASP.NET</h3>  
  5.             <div class="card">  
  6.                 <div class="card-header bg-primary text-white">  
  7.                     <h5 class="card-title">Employee Information</h5>  
  8.                 </div>  
  9.                 <div class="card-body">  
  10.                     <div class="row">  
  11.                         <div class="col-sm-9 col-md-9 col-xs-12">  
  12.                             <div class="row">  
  13.                                 <div class="col-sm-6 col-md-6 col-xs-12">  
  14.                                     <div class="form-group">  
  15.                                         <label>First Name</label>  
  16.                                         <div class="input-group">  
  17.                                             <div class="input-group-prepend">  
  18.                                                 <span class="input-group-text"><i class="fa fa-user"></i></span>  
  19.                                             </div>  
  20.                                             <asp:TextBox ID="txtFisrtName" runat="server" CssClass="form-control"></asp:TextBox>  
  21.                                         </div>  
  22.                                         <asp:RequiredFieldValidator ID="rfvFirstName" ControlToValidate="txtFisrtName" CssClass="text-danger" runat="server" ErrorMessage="First Name is required."></asp:RequiredFieldValidator>  
  23.                                     </div>  
  24.                                 </div>  
  25.                                 <div class="col-sm-6 col-md-6 col-xs-12">  
  26.                                     <div class="form-group">  
  27.                                         <label>Last Name</label>  
  28.                                         <div class="input-group">  
  29.                                             <div class="input-group-prepend">  
  30.                                                 <span class="input-group-text"><i class="fa fa-user"></i></span>  
  31.                                             </div>  
  32.                                             <asp:TextBox ID="txtLastName" runat="server" CssClass="form-control"></asp:TextBox>  
  33.                                         </div>  
  34.                                         <asp:RequiredFieldValidator ID="rvfLastName" ControlToValidate="txtLastName" CssClass="text-danger" runat="server" ErrorMessage="Last Name is required."></asp:RequiredFieldValidator>  
  35.                                     </div>  
  36.                                 </div>  
  37.                             </div>  
  38.                             <div class="row">  
  39.                                 <div class="col-sm-6 col-md-6 col-xs-12">  
  40.                                     <div class="form-group">  
  41.                                         <label>Gender</label>  
  42.                                         <div class="input-group">  
  43.                                             <div class="input-group-prepend">  
  44.                                                 <span class="input-group-text"><i class="fa fa-user"></i></span>  
  45.                                             </div>  
  46.                                             <asp:DropDownList ID="ddlGender" runat="server" CssClass="custom-select">  
  47.                                                 <asp:ListItem Value="-1">Choose Gender</asp:ListItem>  
  48.                                                 <asp:ListItem>Male</asp:ListItem>  
  49.                                                 <asp:ListItem>Female</asp:ListItem>  
  50.                                             </asp:DropDownList>  
  51.                                         </div>  
  52.                                         <asp:RequiredFieldValidator ID="rfvGender" ControlToValidate="ddlGender" InitialValue="-1" CssClass="text-danger" runat="server" ErrorMessage="Choose gender."></asp:RequiredFieldValidator>  
  53.                                     </div>  
  54.                                 </div>  
  55.                                 <div class="col-sm-6 col-md-6 col-xs-12">  
  56.                                     <div class="form-group">  
  57.                                         <label>Date of Birth</label>  
  58.                                         <div class="input-group">  
  59.                                             <div class="input-group-prepend">  
  60.                                                 <span class="input-group-text"><i class="fa fa-calendar"></i></span>  
  61.                                             </div>  
  62.                                             <asp:TextBox ID="txtDateofBirth" runat="server" CssClass="form-control"></asp:TextBox>  
  63.                                         </div>  
  64.                                         <asp:RequiredFieldValidator ID="rfvDateofBith" ControlToValidate="txtDateofBirth" CssClass="text-danger" runat="server" ErrorMessage="Choose date of birth."></asp:RequiredFieldValidator>  
  65.                                     </div>  
  66.                                 </div>  
  67.                             </div>  
  68.                             <div class="row">  
  69.                                 <div class="col-sm-6 col-md-6 col-xs-12">  
  70.                                     <div class="form-group">  
  71.                                         <label>Phone Number</label>  
  72.                                         <div class="input-group">  
  73.                                             <div class="input-group-prepend">  
  74.                                                 <span class="input-group-text"><i class="fa fa-phone"></i></span>  
  75.                                             </div>  
  76.                                             <asp:TextBox ID="txtPhoneNumber" runat="server" CssClass="form-control"></asp:TextBox>  
  77.                                         </div>  
  78.                                         <asp:RequiredFieldValidator ID="rfvPhoneNumber" ControlToValidate="txtPhoneNumber" CssClass="text-danger" runat="server" ErrorMessage="Phone Number is required."  Display="Dynamic"></asp:RequiredFieldValidator>  
  79.                                         <asp:RegularExpressionValidator ID="revPhoneNumber" ControlToValidate="txtPhoneNumber" runat="server" ErrorMessage="Please enter digit only" Display="Dynamic" ValidationExpression="^([7-9]{1})([0-9]{9})$" CssClass="text-danger"></asp:RegularExpressionValidator>  
  80.                                     </div>  
  81.                                 </div>  
  82.                                 <div class="col-sm-6 col-md-6 col-xs-12">  
  83.                                     <div class="form-group">  
  84.                                         <label>Email</label>  
  85.                                         <div class="input-group">  
  86.                                             <div class="input-group-prepend">  
  87.                                                 <span class="input-group-text"><i class="fa fa-envelope"></i></span>  
  88.                                             </div>  
  89.                                             <asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox>  
  90.                                         </div>  
  91.                                         <asp:RequiredFieldValidator ID="rfvEmail" ControlToValidate="txtEmail" CssClass="text-danger" runat="server" ErrorMessage="Email is required." Display="Dynamic"></asp:RequiredFieldValidator>  
  92.                                         <asp:RegularExpressionValidator ID="revEmail" ControlToValidate="txtEmail" runat="server" ErrorMessage="Please enter valid email" Display="Dynamic" CssClass="text-danger" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>  
  93.                                     </div>  
  94.                                 </div>  
  95.                             </div>  
  96.                         </div>  
  97.                         <div class="col-sm-3 col-md-3 col-xs-12">  
  98.                             <asp:Image ID="imagePreview" runat="server" CssClass="img-thumbnail" ImageUrl="~/images/default-avatar.png" Width="150" Height="175" />  
  99.                             <div class="form-group">  
  100.                                 <label>Profile Image</label>  
  101.                                 <div class="custom-file">  
  102.                                     <asp:FileUpload ID="ProfileFileUpload" runat="server" CssClass="custom-file-input" onchange="ShowImagePreview(this);" />  
  103.                                     <label class="custom-file-label"></label>  
  104.                                 </div>  
  105.                                 <asp:RequiredFieldValidator ID="rfvProfileFileUpload" ControlToValidate="ProfileFileUpload" runat="server" CssClass="text-danger" ErrorMessage="Choose image to upload"></asp:RequiredFieldValidator>  
  106.                             </div>  
  107.                         </div>  
  108.                     </div>  
  109.                     <asp:Button ID="btnReset" runat="server" Text="Reset" CssClass="btn btn-info rounded-0" OnClick="btnReset_Click" />  
  110.                     <asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btn btn-primary rounded-0" OnClick="btnSubmit_Click" />  
  111.                 </div>  
  112.             </div>  
  113.             <asp:Label ID="lblMessage" runat="server"></asp:Label>  
  114.             <asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered">  
  115.                 <Columns>  
  116.                     <asp:BoundField HeaderText="ID" DataField="ID" />  
  117.                     <asp:ImageField HeaderText="Image" DataImageUrlField="Image" ControlStyle-Height="50" ControlStyle-Width="50"></asp:ImageField>  
  118.                     <asp:BoundField HeaderText="First Name" DataField="First_Name" />  
  119.                     <asp:BoundField HeaderText="Last Name" DataField="Last_Name" />  
  120.                     <asp:BoundField HeaderText="Gender" DataField="Gender" />  
  121.                     <asp:BoundField HeaderText="DOB" DataField="DateofBirth" />  
  122.                     <asp:BoundField HeaderText="Phone Number" DataField="Phone_Number" />  
  123.                     <asp:BoundField HeaderText="Email" DataField="Email" />  
  124.                 </Columns>  
  125.             </asp:GridView>  
  126.         </div>  
  127.     </form>  
  128. </body>  

Step-7

Write C# back-end code for Submit button, Reset button, and binding the Grid View. 

  1. using System;  
  2. using System.Data;  
  3. using System.Data.SqlClient;  
  4. using System.Configuration;  
  5. using System.IO;  
  6.   
  7. namespace ShowImagePreviewBeforUpload  
  8. {  
  9.     public partial class ShowImgePreview : System.Web.UI.Page  
  10.     {  
  11.         protected void Page_Load(object sender, EventArgs e)  
  12.         {  
  13.             if (!IsPostBack)  
  14.             {  
  15.                 BindEmployeeGrid();  
  16.             }  
  17.         }  
  18.   
  19.         private void BindEmployeeGrid()  
  20.         {  
  21.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  22.             using (SqlConnection con=new SqlConnection(CS))  
  23.             {  
  24.                 SqlCommand cmd = new SqlCommand("spGetAllEmplyee",con);  
  25.                 cmd.CommandType = CommandType.StoredProcedure;  
  26.                 con.Open();  
  27.                 EmployeeGridView.DataSource=cmd.ExecuteReader();  
  28.                 EmployeeGridView.DataBind();  
  29.             }  
  30.         }  
  31.   
  32.         protected void btnSubmit_Click(object sender, EventArgs e)  
  33.         {  
  34.             try  
  35.             {  
  36.                 if (ProfileFileUpload.PostedFile != null)  
  37.                 {  
  38.                     string FileName = Path.GetFileName(ProfileFileUpload.PostedFile.FileName);  
  39.                     ProfileFileUpload.SaveAs(Server.MapPath("/images" + FileName));  
  40.                     string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  41.                     using (SqlConnection con = new SqlConnection(CS))  
  42.                     {  
  43.                         SqlCommand cmd = new SqlCommand("spAddNewlEmplyee", con);  
  44.                         cmd.CommandType = CommandType.StoredProcedure;  
  45.                         con.Open();  
  46.                         cmd.Parameters.AddWithValue("@First_Name",txtFisrtName.Text.Trim());  
  47.                         cmd.Parameters.AddWithValue("@Last_Name",txtLastName.Text.Trim());  
  48.                         cmd.Parameters.AddWithValue("@Gender",ddlGender.SelectedItem.Value);  
  49.                         cmd.Parameters.AddWithValue("@DateofBirth",txtDateofBirth.Text.Trim());  
  50.                         cmd.Parameters.AddWithValue("@Phone_Number",txtPhoneNumber.Text.Trim());  
  51.                         cmd.Parameters.AddWithValue("@Email",txtEmail.Text.Trim());  
  52.                         cmd.Parameters.AddWithValue("@Image","images"+ FileName);  
  53.                         cmd.Parameters.AddWithValue("@Created", DateTime.Now);  
  54.                         cmd.ExecuteNonQuery();  
  55.                         BindEmployeeGrid();  
  56.                         lblMessage.Text = "Your record submitted successfully";  
  57.                         lblMessage.ForeColor = System.Drawing.Color.Green;  
  58.   
  59.                     }  
  60.                 }  
  61.             }  
  62.             catch (Exception)  
  63.             {  
  64.                 lblMessage.Text = "Your record not submitted";  
  65.                 lblMessage.ForeColor = System.Drawing.Color.Red;  
  66.             }  
  67.         }  
  68.   
  69.         protected void btnReset_Click(object sender, EventArgs e)  
  70.         {  
  71.             txtFisrtName.Text= string.Empty;  
  72.             txtLastName.Text = string.Empty;  
  73.             txtDateofBirth.Text = string.Empty;  
  74.             txtPhoneNumber.Text = string.Empty;  
  75.             txtEmail.Text = string.Empty;  
  76.         }  
  77.     }  
  78. }  

Step 8

Run the project by pressing ctr+F5.

ASP.NET
ASP.NET
ASP.NET
ASP.NET