Image Upload and View on SQL Server in ASP.Net With Automatic ID Generation

This article helps you to upload your images to an ASP.NET website and store all the details regarding the image in a SQL Server database.

Step 1: Creating Database to store image information

Create a database ImagesDB on SQL Server with Windows Authentication and create a table [ImagesTB] with this structure: 

Column Name Column Type
ImageId Varchar(50)
ImageName Varchar(50)
UploadDate Varchar(50)
UploadTime Varchar(50)

Step 2: Creating a Web form to upload image

Now we need to create a webpage to get the image details from the user that looks like:

image upload

I created a method [createid()] to generate an automatic imageid.

  1. private string createid()  
  2. {  
  3.       SqlConnection con = new SqlConnection();  
  4.       con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["imageconnection"].ConnectionString;  
  5.       string qry = "select top 1 ImageId from ImageTB order by ImageId desc";  
  6.       SqlCommand cmd = new SqlCommand(qry, con);  
  7.       string id = "";  
  8.       try  
  9.       {  
  10.             con.Open();  
  11.             id = Convert.ToString(cmd.ExecuteScalar());  
  12.             con.Close();  
  13.       }  
  14.       catch (SqlException ex)  
  15.       {  
  16.             Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");  
  17.       }  
  18.       if (id == "")  
  19.       {  
  20.             id = "pic001";  
  21.       }  
  22.       else if (id != "")  
  23.       {  
  24.             string id1 = id.Substring(3, id.Length - 3);  
  25.             int i = Convert.ToInt32(id1);  
  26.             i++;  
  27.             if (i >= 1 && i < 10)  
  28.             {  
  29.                   id = "pic00" + i;  
  30.             }  
  31.             else if (i >= 10 && i < 100)  
  32.             {  
  33.                   id = "pic0" + i;  
  34.             }  
  35.             else if (i >= 100)  
  36.             {  
  37.                   id = "pic" + i;  
  38.             }  
  39.       }  
  40.       return id;  
  41. }
And another methed to upload the image to the web server. My website has a folder called UploadedImages that contains all the uploaded images.
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.       string fn = "";  
  4.       string id = "";  
  5.       String fileExtension;  
  6.       Boolean fileOK;  
  7.       String[] allowedExtensions = { ".gif"".png"".jpeg"".jpg"".bmp" };  
  8.   
  9.       fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();  
  10.       fileOK = false;  
  11.   
  12.       for (int i = 0; i < allowedExtensions.Length; i++)  
  13.       {  
  14.             if (fileExtension == allowedExtensions[i])  
  15.             {  
  16.                   fileOK = true;  
  17.             }  
  18.       }  
  19.   
  20.       if (fileOK)  
  21.       {  
  22.             fn = TextBox1.Text + fileExtension;  
  23.             if (TextBox2.Text == "")  
  24.             {  
  25.                   TextBox2.Text = TextBox1.Text;  
  26.             }  
  27.   
  28.             SqlConnection con = new SqlConnection();  
  29.             con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["imageconnection"].ConnectionString;  
  30.             SqlCommand cmd = new SqlCommand("insert into imageTB(ImageId,ImageName,ImagePath,UploadDate,UploadTime) values(@a,@b,@c,@d,@ee)", con);  
  31.             cmd.Parameters.Add("@a", SqlDbType.VarChar, 50).Value = TextBox1.Text;  
  32.             cmd.Parameters.Add("@b", SqlDbType.VarChar, 50).Value = TextBox2.Text;  
  33.             cmd.Parameters.Add("@c", SqlDbType.VarChar, 50).Value = "~/UploadedImages/" + TextBox1.Text+fileExtension;  
  34.             cmd.Parameters.Add("@d", SqlDbType.VarChar, 50).Value = Label5.Text;  
  35.             cmd.Parameters.Add("@ee", SqlDbType.VarChar, 50).Value = Label7.Text;  
  36.   
  37.             try  
  38.             {  
  39.                   con.Open();  
  40.                   int status=cmd.ExecuteNonQuery();  
  41.                   if (status > 0)  
  42.                   {  
  43.                         String path = Server.MapPath("~/UploadedImages/");  
  44.                         FileUpload1.PostedFile.SaveAs(path + fn);  
  45.                         Label9.Text = TextBox2.Text + " is uploaded";  
  46.                         Label9.ForeColor = System.Drawing.Color.Green;  
  47.                         TextBox1.Text = createid();  
  48.                         TextBox2.Text = "";  
  49.                         Label5.Text = System.DateTime.Now.ToShortDateString();  
  50.                         Label7.Text = System.DateTime.Now.ToShortTimeString();  
  51.                   }  
  52.                   else  
  53.                   {  
  54.                         Label9.Text = "Image is not uploaded";  
  55.                         Label9.ForeColor = System.Drawing.Color.Red;  
  56.                   }  
  57.   
  58.   
  59.             }  
  60.             catch (SqlException ex)  
  61.             {  
  62.                   Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");  
  63.             }  
  64.             finally  
  65.             {  
  66.                   con.Close();  
  67.             }  
  68.       }  
  69.       else  
  70.       {  
  71.             Response.Write("<script>alert('Invalid file format')</script>");  
  72.             TextBox2.Text = "";  
  73.             Label5.Text = System.DateTime.Now.ToShortDateString();  
  74.             Label7.Text = System.DateTime.Now.ToShortTimeString();  
  75.       }  
  76. }  
Step 3: Creating a Web form to View image

Now we are creating a webform to view images. All we need to do is to load all the image names from the database to a listbox, then by selecting an image name from the listbox we need to display the image in an asp:image control.

view image 
  1. Loading an image name to a listbox at Page_Load event:
    1. protected void Page_Load(object sender, EventArgs e)  
    2. {  
    3.       if (!IsPostBack)  
    4.       {  
    5.             SqlConnection con = new SqlConnection();  
    6.             con.ConnectionString System.Configuration.ConfigurationManager.ConnectionStrings["imageconnection"].ConnectionString;  
    7.   
    8.             SqlDataAdapter ad = new SqlDataAdapter("Select * from imagetb", con);  
    9.   
    10.             DataTable dt = new DataTable();  
    11.   
    12.             ad.Fill(dt);  
    13.   
    14.             for (int i = 0; i < dt.Rows.Count; i++)  
    15.             {  
    16.                   ListBox1.Items.Add(dt.Rows[i][1].ToString());  
    17.             }  
    18.       }  
  2. Loading an image to an image control:
    1. protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)  
    2. {  
    3.       SqlConnection con = new SqlConnection();  
    4.       con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["imageconnection"].ConnectionString;  
    5.       con.Open();  
    6.       SqlDataAdapter ad = new SqlDataAdapter("Select * from imagetb", con);  
    7.       con.Close();  
    8.       DataTable dt = new DataTable();  
    9.   
    10.       ad.Fill(dt);  
    11.   
    12.       Image1.ImageUrl= dt.Rows[ListBox1.SelectedIndex][2].ToString();  
    13.   
    14.       dt.Dispose();  
    15. }  

Up Next
    Ebook Download
    View all
    Learn
    View all