This tutorial will show you how to both save an image, and also retrieve the image from a SQL database. C# version.
We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with! Looking for more .NET Database Tutorials? Click Here!
There are many tutorials out there that show you how to store images in a database, but not many show you how to retrieve images and display them inline. It is pretty tricky to do, unfortunately, but it can be done. This tutorial will show you how to use the FileUpload control to save an image to the database and then also display it inline, in the same page, with all the other controls.
Our first step is to create the database. We will have one table with three columns- id, title and image. The image column will be of type image, also. Once we have our database set up, we can start work on the ASPX page. We will add a textbox for the title, a FileUpload Control for the image, and a button to initiate the upload. Finally, we will include an Image placeholder, which will display the image when it has been uploaded. Our ASPX page will look something like this:
<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> |
Nothing too special right now, just a regular ASPX page with a few controls. Next, we are going to want to add the logic to the button click event - notice that we have already specified the method in the OnClick attribute of the button. In the code-behind, the butSubmit_Click will look something like this:
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 chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar. In this method, we get the file from the FileUpload control and also the text entered by the user, then we transfer this data over to the database. We also set the ImageUrl of the Image placeholder to point at a HttpHandler we are about to create. Right-click your project and choose to Add New Item > Generic Handler. In this file, we will add the following:
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(); } } |
In this handler, we are receiving the id of the database record in a querystring, then locating it in the database to retrieve the image bytes. We then use a MemoryStream object to display the image. The entire code for this handler is as follows:
<%@ WebHandler Language="C#" Class="DisplayImg" %>
using System; using System.Web; using System.Configuration; using System.IO; using System.Data; using System.Data.SqlClient;
public class DisplayImg : IHttpHandler {
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(); } } public bool IsReusable {
} } |
Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we've found so far.
Looking for more .NET Database Tutorials? Click Here!
|