What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 18926 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > Saving images into the database in asp.net and displaying to the GridView

Saving images into the database in asp.net and displaying to the GridView

3 vote(s)
Rating: 4.33 out of 5
Article posted by SheoNarayan on 11/29/2010 | Views: 33748 | Category: ASP.NET | Level: Intermediate | Points: 250 red flag


This article describes how to save an image file into the database and show them in the GridView.

Download


 Download source code for Saving images into the database in asp.net and displaying to the GridView


Introduction

This article has been written in the response of the question asked in this Forum thread http://www.dotnetfunda.com/forums/thread2974-explanation-about-ashx-pagehandler-page-with-example.aspx where the author was able to save the image into database successfully but couldn't show the record into the GridView.

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.

Get solutions of your .NET problems with video explanations and source code in .NET How to's.

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 PictureFile column is of Image data type.

To show the saving and displaying image from database, I have created 3 pagese

  1. default.aspx - to save the image into the database
  2. ShowImage.aspx - to show the records including the image into the gridview
  3. 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 using PostedFile.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 IsReusable method 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!

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: Sadnaisik | Posted on: 06 Feb 2013 09:19:37 AM | Points: 25

Hello,
First Thank you very much for the tutorials. I am trying to do above asp. net image upload procedure. Could you please explain how to connect to DB. I meant to upload and save it to DB. I tried my best but I could not .
Regards

>> Write Response - Respond to this post and get points
Related Posts

This article deals with validating the FileUpload control which is inside a GridView control.

Yesterday I stumbled across a post that was posted on our forum. I was very busy with other things, when Sheo started a conversation based on that post. I was looking at it until he updated the untagged code that was posted. By looking at the Stored Procedure I could see that the poster was lost and his Stored Procedure approach failed him. In this Article am going to explain how to write a simple login in Asp.net.

This article shows how to get Selected record key value from GridView, DataList, FormView, DetailsView, ListView, and Repeater controls.

This article is useful for displaying shadow

Till now we have not created any screen for data entry. In this tutorial we will create a simple data entry, flourish a simple model and display the model on a simple ASP.NET view.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/25/2013 5:34:28 AM