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. fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
  9. fileOK = false;
  10. for (int i = 0; i < allowedExtensions.Length; i++)
  11. {
  12. if (fileExtension == allowedExtensions[i])
  13. {
  14. fileOK = true;
  15. }
  16. }
  17. if (fileOK)
  18. {
  19. fn = TextBox1.Text + fileExtension;
  20. if (TextBox2.Text == "")
  21. {
  22. TextBox2.Text = TextBox1.Text;
  23. }
  24. SqlConnection con = new SqlConnection();
  25. con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["imageconnection"].ConnectionString;
  26. SqlCommand cmd = new SqlCommand("insert into imageTB(ImageId,ImageName,ImagePath,UploadDate,UploadTime) values(@a,@b,@c,@d,@ee)", con);
  27. cmd.Parameters.Add("@a", SqlDbType.VarChar, 50).Value = TextBox1.Text;
  28. cmd.Parameters.Add("@b", SqlDbType.VarChar, 50).Value = TextBox2.Text;
  29. cmd.Parameters.Add("@c", SqlDbType.VarChar, 50).Value = "~/UploadedImages/" + TextBox1.Text+fileExtension;
  30. cmd.Parameters.Add("@d", SqlDbType.VarChar, 50).Value = Label5.Text;
  31. cmd.Parameters.Add("@ee", SqlDbType.VarChar, 50).Value = Label7.Text;
  32. try
  33. {
  34. con.Open();
  35. int status=cmd.ExecuteNonQuery();
  36. if (status > 0)
  37. {
  38. String path = Server.MapPath("~/UploadedImages/");
  39. FileUpload1.PostedFile.SaveAs(path + fn);
  40. Label9.Text = TextBox2.Text + " is uploaded";
  41. Label9.ForeColor = System.Drawing.Color.Green;
  42. TextBox1.Text = createid();
  43. TextBox2.Text = "";
  44. Label5.Text = System.DateTime.Now.ToShortDateString();
  45. Label7.Text = System.DateTime.Now.ToShortTimeString();
  46. }
  47. else
  48. {
  49. Label9.Text = "Image is not uploaded";
  50. Label9.ForeColor = System.Drawing.Color.Red;
  51. }
  52. }
  53. catch (SqlException ex)
  54. {
  55. Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");
  56. }
  57. finally
  58. {
  59. con.Close();
  60. }
  61. }
  62. else
  63. {
  64. Response.Write("<script>alert('Invalid file format')</script>");
  65. TextBox2.Text = "";
  66. Label5.Text = System.DateTime.Now.ToShortDateString();
  67. Label7.Text = System.DateTime.Now.ToShortTimeString();
  68. }
  69. }
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. SqlDataAdapter ad = new SqlDataAdapter("Select * from imagetb", con);
    8. DataTable dt = new DataTable();
    9. ad.Fill(dt);
    10. for (int i = 0; i < dt.Rows.Count; i++)
    11. {
    12. ListBox1.Items.Add(dt.Rows[i][1].ToString());
    13. }
    14. }
    15. }
  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. ad.Fill(dt);
    10. Image1.ImageUrl= dt.Rows[ListBox1.SelectedIndex][2].ToString();
    11. dt.Dispose();
    12. }