Learn How to Retrieve an Image From a Database with ASP.NET 4.0 and C#
Introduction
This tutorial will show you not only how to save an image to a SQL database, but how to retrieve the image and display it on your web page. C#. Storing images to a database is relatively easy, but retrieving them to display in pages is probably a bit more difficult than it should be. In this tutorial, you will learn not only how to save images to a SQL database, but also how to retrieve them and display it on the page with the other controls, inline.
In this example, we are going to use a SQL database with one table, and three columns – id, title and image. Once we have our database set up, we can start on our ASPX page.
We stand behind Server Intellect and their whole support team, they offer dedicated servers of course, and they now offer the cloud, which is nice.
We are going to use a simple form consisting of a textbox, a file upload control, and a button. We will also include a label for status messages, and an image control as a placeholder for our uploaded image. Which will look something like this:
This is all we will be adding on our ASPX page, the rest of the web application will be the code-behind and a generic handler. We will start on the code-behind, first. Notice above that we have already set our onclick handler to a method. In the code-behind, we will code the button click event to open a connection with the SQL Database.
This is the only method in the code-behind. What it does in essence, is capture the bytes of the uploaded file, and then saves this to the database along with the text input into the title field. Notice at the end of the try statement we have set the ImageUrl of our image placeholder. This points to the http handler we are going to create. Right-click your project in Solution Explorer and choose Add New Item.. > Generic Handler. Name it DisplayImg.ashx and then add the following code:
We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers of course, and they now offer the cloud, which is nice.
In this handler, we are receiving the id of the database record in a query string, then locating it in the database to retrieve the image bytes. We then use a MemoryStream object to display the image.
Conclusion
In this tutorial we learned how to save and retrieve an image from an SQL database. This can be very useful for large scale sites that need to store images on a server rather than locally.
We used over 10 web hosting companies before we found Server Intellect. Our new cloud server,was set up in less than 24 hours. We were able to confirm our order over the phone. They responded to our inquiries within an hour. Server Intellect’s customer support and assistance are the best we’ve ever experienced.
SaveRetrieveImageDatabase-cs.zip
This tutorial will show you not only how to save an image to a SQL database, but how to retrieve the image and display it on your web page. C#. Storing images to a database is relatively easy, but retrieving them to display in pages is probably a bit more difficult than it should be. In this tutorial, you will learn not only how to save images to a SQL database, but also how to retrieve them and display it on the page with the other controls, inline.
In this example, we are going to use a SQL database with one table, and three columns – id, title and image. Once we have our database set up, we can start on our ASPX page.
We stand behind Server Intellect and their whole support team, they offer dedicated servers of course, and they now offer the cloud, which is nice.
We are going to use a simple form consisting of a textbox, a file upload control, and a button. We will also include a label for status messages, and an image control as a placeholder for our uploaded image. Which will look something like this:
Code Block
Default.aspx
Controls for User Interface<form id="form1" runat="server">Title: <asp:TextBox ID="txtTitle" runat="server" /><br />
Image: <asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="butSubmit" runat="server" Text="Submit"
onclick="butSubmit_Click" /><br />
<asp:Label ID="lblStatus" runat="server"></asp:Label>
<br /><br />
<asp:Image ID="Image1" runat="server" />
</form>
Code Block
Default.aspx.cs
protected void butSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
{
Byte[] imgByte = null;
if (FileUpload1.HasFile && FileUpload1.PostedFile != null)
{
HttpPostedFile File = FileUpload1.PostedFile;
imgByte = new Byte[File.ContentLength];
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
connection = new SqlConnection(ConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString.ToString());
connection.Open();
string sql = "INSERT INTO Table1(title,image) VALUES(@theTitle, @theImage) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@theTitle", txtTitle.Text);
cmd.Parameters.AddWithValue("@theImage", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblStatus.Text = String.Format("ID is {0}", id);
Image1.ImageUrl = "~/DisplayImg.ashx?id=" + id;
}
catch
{
lblStatus.Text = "There was an error";
}
finally
{
connection.Close();
}
}
We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers of course, and they now offer the cloud, which is nice.
Code Block
Default.aspx
public void ProcessRequest (HttpContext context)
{
Int32 theID;
if (context.Request.QueryString["id"] != null) {
theID = Convert.ToInt32(context.Request.QueryString["id"]); }
else {
throw new ArgumentException("No parameter specified");
}
context.Response.ContentType = "image/jpeg";
Stream strm = DisplayImage(theID);
byte[] buffer = new byte[2048];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
public Stream DisplayImage(int theID)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString());
string sql = "SELECT image FROM Table1 WHERE id = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", theID);
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
Conclusion
In this tutorial we learned how to save and retrieve an image from an SQL database. This can be very useful for large scale sites that need to store images on a server rather than locally.
We used over 10 web hosting companies before we found Server Intellect. Our new cloud server,was set up in less than 24 hours. We were able to confirm our order over the phone. They responded to our inquiries within an hour. Server Intellect’s customer support and assistance are the best we’ve ever experienced.
SaveRetrieveImageDatabase-cs.zip
