Skip to main content

How to upload images to SQLServer database

Upload image using FileUpload
                                                                   Asp FileUpload use to upload file, using this we can upload image to server and save location of where it store in server for later useit.

<asp:FileUpload ID="file_img"  runat ="server" />

                 <asp:RequiredFieldValidator ID="RFV-1" runat ="server" 
                      ControlToValidate ="file_img" ErrorMessage ="Please upload logo of college or Event" SetFocusOnError="true" ></asp:RequiredFieldValidator>

                <asp:RegularExpressionValidator ID="RFV_2"   SetFocusOnError ="true" 
                     runat="server" ErrorMessage="Please Upload file Invalid File!(only  .gif, .jpg, .jpeg, .wav Files are supported)" ValidationExpression="^.+(.jpg|.JPG|.gif|.GIF|.png|.PNG|.jpeg|JPEG)$" 
  1. The first RFV_1 asp:RequiredFieldValidator  use to check non empty submit.
  2. The second RFV_2 asp:RequiredFieldValidator  will restrict user to upload only .jpg|.JPG|.gif|.GIF|.png|.PNG|.jpeg|JPEG)  type of files.

In Code Behind page Vb.Net

Imports System.Data.SqlClient
Imports System.Data

 Protected Sub btt_submit_Click(sender As Object, e As EventArgs)
        Dim imgname, imgpath As String
        imgname = file_img.FileName    // Get image name
        imgpath = "~/Images/" + imgname  // Map file  location in server
        file_img.SaveAs(Server.MapPath(imgpath))  // Upload image file
        Dim strconn As String
        strconn = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
        ' for opening db connection
        Dim con As New SqlConnection(strconn)
        Dim cmd As New SqlCommand
        cmd. = con
        cmd.CommandText = "job_insert"
        cmd.CommandType = CommandType.StoredProcedure // call store procedure or you can use normal insert query       
        cmd.Parameters.Add(New SqlParameter("@image_url", imgpath)) // save image location in table filed image_url.

ImageName     Image_url
 Img1  ~/images/Img2.jpg
 Img2     ~/images/Img2.jpg

As in above image table we use to store image location rather than storing image in binary format.

To display image we using image tag as
 <asp:Image ID="gvimg" runat="server" ImageUrl='<%#Eval("imageurl")%>' Width ="100px" Height ="100px" />                                 


  1. Display image from Database to page.


Post a Comment