How to save images in database and retrieve image from database
-Joseph Paul Moonjely
Hello friends
In this article, we will explore how to store images in the database and then display those images along with the other server controls
Today I am going to show how you can save image from web page to database using asp File Upload Control and retrieve same image . There might be various approaches for this I am going show one of them
Using handlers : by converting image into binary format
I am going to a build a form, with the person’s details and his photo along with it, or for that case, display the image in an ASP.NET server control along with other controls?
Let us start off by first creating a sample database and adding a table to it. We will call the database and the table will be called ‘Tbl_Emp’
Database structure will be like this
Step 1: Create a new asp.net website and add a webpage to it
Step2: Drag and drop two textbox controls. Also drag drop a File Upload control and two button control to upload the selected image on button click and to retrieve record from database. Dropdown List to select list ID which will be used to retrieve selected record from database
Aspx page code will look like below
<div>
Enter ID <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
Enter Name <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
Enter Pic <asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" /><br >
<asp:Image ID="Image1" runat="server" Height="137px" Width="130px" /><br />
<asp:DropDownList ID="TextBox3" runat="server">
</asp:DropDownList>
<asp:Button ID="Button2" runat="server" Text="Search" onclick="Button2_Click" />
</div>
Step3: code on .cs page
On my code there are three methods
Filldropdown() : used to fill dropdown
Button1_Click : used to save image into database
Button2_Click : used to retrieve image from database
static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
filldropdown();
}
}
public void filldropdown()
{
SqlCommand cmd = new SqlCommand("Select EmpID from Tbl_Emp", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
TextBox3.Items.Clear();
if (dr.HasRows)
{
//TextBox3.DataSource = dr["EmpID"].ToString();
//TextBox3.DataBind();
while (dr.Read())
{
TextBox3.Items.Add(dr["EmpID"].ToString());
}
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Tbl_Emp values(@id,@name,@image)",con);
cmd.Parameters.AddWithValue("@id", TextBox1.Text);
cmd.Parameters.AddWithValue("@name", TextBox2.Text);
int img = FileUpload1.PostedFile.ContentLength;
byte[] msdata = new byte[img];
FileUpload1.PostedFile.InputStream.Read(msdata,0,img);
cmd.Parameters.AddWithValue("@image", msdata);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd.ExecuteNonQuery();
con.Close();
filldropdown();
Response.Write("Data Saved ....");
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from Tbl_Emp where EmpID=@id", con);
cmd.Parameters.AddWithValue("@id", TextBox3.Text);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows && dr.Read())
{
TextBox1.Text = dr["EmpID"].ToString();
TextBox2.Text = dr["EmpName"].ToString();
Image1.ImageUrl = "Handler.ashx?EmpID=" + TextBox3.Text;
}
else
{
Response.Write("Record With This ID Note Found");
}
}
Step 4: In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > Handler.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the EmpID from it. The ID is then passed to this handler from drop on button 2 click
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
public class Handler : IHttpHandler {
static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
public void ProcessRequest (HttpContext context) {
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
SqlCommand cmd = new SqlCommand("select EmpPic from Tbl_Emp where EmpID=@EmpID",con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd.Parameters.AddWithValue("@EmpID", context.Request.QueryString["EmpID"].ToString());
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows && dr.Read())
{
context.Response.BinaryWrite((byte[])(dr["EmpPic"]));
}
con.Close();
}
public bool IsReusable {
get {
return false;
}
}
}
I hope this article was useful