Introduction
Namespace used in this article
You will need to use System.IO, System.Configuration, System.Data, System.Data.SqlClient namespaces in order to achive the solution described in this article.
ImageUpload Database table structure
In order to show how to save and read the image from database, I have created a sample table and its strucure similar to below mentioned table.
Here my AutoId column is autoincrement column and rest of the columns are self explained in the picture. One thing to note is that PictureFilecolumn is of Image data type.
To show the saving and displaying image from database, I have created 3 pagese
- default.aspx - to save the image into the database
- ShowImage.aspx - to show the records including the image into the gridview
- ShowImage.ashx (Generic Hanlder file) - to retrive the image from the database and give it to ShowImage.aspx as Binary data to its html img tag
Saving image to the database in asp.net
The code to save the image into the database is written in default.aspx in my sample app and here is the code for the default.aspx page
Select file to save into the database:
<asp:FileUpload runat="server" ID="FileUpload1" />
<asp:Button runat="server" ID="btnSave" OnClick="SaveToTheDatabase" Text="Save to the database" />
<p><asp:Label ID="lblMessage" runat="server" EnableViewState="false" /></p>
Notice that when Save ... button will be clicked, I have fired SaveToTheDatabase method and below is the code snippet for this method.
protected void SaveToTheDatabase(object sender, EventArgs e)
{
string fileName = FileUpload1.PostedFile.FileName;
int fileLength = FileUpload1.PostedFile.ContentLength;
byte[] imageBytes = new byte[fileLength];
FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, fileLength);
string connStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
string sql = "INSERT INTO ImageUpload (PictureName, PictureFile) VALUES (@pictureName, @pictureFile)";
SqlParameter[] prms = new SqlParameter[2];
prms[0] = new SqlParameter("@pictureName", SqlDbType.VarChar, 50);
prms[0].Value = fileName;
prms[1] = new SqlParameter("@pictureFile", SqlDbType.Image);
prms[1].Value = imageBytes;
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(prms);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
lblMessage.Text = "Picture uploaded successsfully !";
}
}
In the above code snippet, first I have retrieved the complete file name of the image, then retrieved the length of the image content usingPostedFile.ContentLength property of FileUpload control.
The next line is to create the array of bytes and read the entire image into it.
Rest of the code snippets are self explanatory in which I have used ADO.NET to save the records into the database. One important thing to note is that as my PictureFile column is of type Image I will have to specify the Image data type of SqlDbType in the SqlParameter.
This way we have saved the image into the database successfully, now lets try to read the image from the database in the next page.
Show image from database into GridView
I am displaying the image from the database into ShowImage.aspx page and here is the code for that.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="AutoID" DataField="AutoID" />
<asp:BoundField HeaderText="Picture Name" DataField="PictureName" />
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<img src="ShowImage.ashx?autoid=<%# Eval("AutoId").ToString() %>" width="150" height="100" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Notice ItemTemplate code for the Picture column, I have used an img tag and specified its src attribute as a generic handler file (.ashx) that I am going to describe later in this article.
Below is the code for the code behind of the ShowImage.aspx page
protected void Page_Load(object sender, EventArgs e)
{
string connStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStr))
{
string sql = "SELECT AutoID, PictureName FROM ImageUpload ORDER BY PictureName";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
conn.Open();
ad.Fill(table);
conn.Close();
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
In the above code snippet, I have used ADO.NET to retrive the records of the ImageUpload table and bounded to the GridView.
As I had specified ShowImage.ashx generic handler (.ashx) as src attribute of the img tag in the Picture column of GridView, so lets write code for this handler file.
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["autoId"] == null) return;
string connStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
string pictureId = context.Request.QueryString["autoId"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT PictureFile FROm ImageUpload WHERE AutoID = @autoId", conn))
{
cmd.Parameters.Add(new SqlParameter("@autoId", pictureId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("PictureFile")]);
reader.Close();
}
}
}
}
public bool IsReusable
{
get
{
return true;
}
}
In the above code snippet, I am checking for the autoId querystring, if its null I am simply returning.
Next line is to get the querystring value, retrive the image content from the database (PictureFile column) and writing it as Binary. The IsReusablemethod is the default method that comes with the generic handler, I have changed its return type to true so that same can be reused.
If you have followed the steps I have described above you should be ready to run the application. Run it and start saving records into the database (default.aspx), go to the ShowImage.aspx page and you should be able to see images in the GridView.
Conclusion
Hope this will be useful for the author of the Forum thread for which I have written this article; apart from that this should be useful for others who are looking for solution of saving images into the database and showing into the Grid.
Thanks for reading!