Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Asp.

Net C# Code to Upload Image to Database


Updated on 17 Apr 2012, Published on 16 Feb 2008

In ASP.Net 2.0 you can use SQL Database to store images. SQL database has a datatype image that can store binary stream of images passed by the ASP.Net code. You can use the following structure to store the image in SQL Database:
Database Columns

img_id img_title img_stream img_type

Create img_id field as a primary key auto increment id for an image. img_title a varchar datatype field to store the title of the image. img_stream having image datatype field to store the binary stream of the image. img_type as a varchar field to store the content type i.e. MIME type of the image. E.g.: image/jpeg, image/gif etc. Required namespaces in ASP.Net C# code to apply the proper functions and parsing the posted image into the binary format are:
view plaincopy to clipboardprint?

1. using System.Data; 2. using System.Data.SqlClient; 3. using System.IO;

IO namespace provides the file input-output classes and functions, from which Stream class can be used to cache the image sent by the client using ASP.Net 2.0 file upload server control.
Example
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

int imageSize; string imageType; Stream imageStream;


// Gets the Size of the Image

imageSize = fileImgUpload.PostedFile.ContentLength;
// Gets the Image Type

imageType = fileImgUpload.PostedFile.ContentType;
// Reads the Image stream

imageStream = fileImgUpload.PostedFile.InputStream;

Passing the Posted Files Input Stream to the object of Stream class, image is cached into the memory. Further this stream is converted into array of bytes that can be sent to SQL Database for storage.

Example
view plaincopy to clipboardprint?

1. byte[] imageContent = newbyte[imageSize]; int intStatus; 2. 3. intStatus = imageStream.Read(imageContent, 0, imageSize);

Continue to next tutoria: ASP.Net C# code to load image from dastabase to learn how to load and display image from database and download free ASP.Net 2.0 C#/VB code.

ASP.Net C# Code to Load Image from Database


Updated on 17 Apr 2012, Published on 16 Feb 2008

ASP.Net 2.0 provides number of controls to bind data retrieved from the SQL Database or any other database source like MS Access database. You can get the information about ASP.Net 2.0 Data Access controls from ASP.Net Data Access Controls and Data bound controls from ASP.Net DataBound Controls. From the list of ASP.Net 2.0 Databound controls you can use the GridView Control to display the data as well as image retrieved from the SQL Database. You can use Response.BinaryWrite function of ASP.Net to write the binary stream of an image stored in the SQL Database. But you need a little logic to bind the binary data to image server control placed inside the template column of GridView.
view plaincopy to clipboardprint?

1. publicstring imageURL(string img_id) 2. { 3. return ("retrieveImages.aspx?id=" + img_id); 4. }

Above function can be used to retrieve the image cached in the memory stream. Following code can be used inside the Grid View Control to bind the imageURL function created at server end.
view plaincopy to clipboardprint?

1. <asp:templatefield> 2. <ItemTemplate> 3. <asp:Image ID="imgSaved" 4. runat="server" 5. ImageUrl='<%# imageURL(DataBinder.Eval(Container.DataItem, "img_id").ToS tring()) %>' 6. AlternateText='<%#DataBinder.Eval(Container.DataItem,"img_title") %>'/> 7. </ItemTemplate> 8. </asp:templatefield>

Databinder will pass the image id to the function and then it will retrieve the corresponding image stream from the SQL Database. Following code will write the image stream into the memory:
view plaincopy to clipboardprint?

1. Response.ContentType = dRow["img_type"].ToString(); 2. 3. byte[] imageContent = (byte[])((dRow["img_stream"])); 4. 5. Response.BinaryWrite(imageContent);

You can download the free C# source code of ASP.Net 2.0 to store and load image from SQL Database here: displayImagesCSharp.zip (4.38 kb) displayImagesCSharp.rar (4.09 kb) You can download the free VB source code of ASP.Net 2.0 to display Image from SQL Database here Store and Display Images from Database. Continue to next tutorial: ASP.Net Upload Image to MS Access Database to learn how to upload an images to Microsoft Access database.

Introduction This article explicate the method of inserting images and pictures into SQL Server database table and display it in an Asp.Net GridView control with the help of Handler.aspx. Description Have you seen any web application or website without images? No, you cannot. Images played a major role in web application development. Either its a static html website or an advanced RAD application, everything is build along with images. If your application is an E-Commerce based or Image Gallery portal, definitely you have to suffer lot on saving the images in different location with different sizes and types. And its not an easiest job to manage those unwanted and outdated images to be removed from your file server, then making backup of those images from one server location to another location. So it is clearly time consuming and hectic.

To make your task easier, this article explains you the methods of storing the images into data source. There are many advantages of saving the images into database. The main advantage is easy management of images. You can control the number and size of images stored in your server. You can remove all unnecessary images from the database in a single sql query and you can backup the image data easily. On the other hand, you should be generous of keeping sufficient memory store in your database server.
Inserting Image into Database To start with, let me explain the SQL Server database table structure we are going to use to insert the image. The table you are going to create to store the image must contain a column of data type IMAGE. This image data type is a Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes. To store the image into this column we are going to convert it into binary string with the help of some IO classes and then insert into the table. For demonstration, we are going to create a table named ImageGallery with four columns in the following structure

Column Name Img_Id Image_Content

Description Identity column for Image Id Store the Image in Binary Format

Data Type int image

Image_Type Image_Size
After we create table

Store the Image format (i.e. jpeg, gif, png, varchar etc.) Store the Image File Size bigint
in the database, we can start the coding part.

1. Open your web application in Visual Studio 2005, drag and drop File Upload control and a Button control into the web page. 2. In the code-behind, add the namespace System.IO.
using System.IO;

3. In the Buttons Button1_Click event, write the following code


if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") { byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength]; HttpPostedFile Image = FileUpload1.PostedFile; Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength); SqlConnection myConnection = new SqlConnection(Your Connection String); SqlCommand storeimage = new SqlCommand("INSERT INTO ImageGallery " +"(Image_Content, Image_Type, Image_Size) " +" values (@image, @imagetype, @imagesize)", myConnection); storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage; storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value = FileUpload1.PostedFile.ContentType; storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value = FileUpload1.PostedFile.ContentLength; myConnection.Open(); storeimage.ExecuteNonQuery(); myConnection.Close(); }

To upload the image from any location (your local drive) to the server, we have to use HttpPostedFile object. Point the uploaded file to HttpPostedFile object. Then the InputStream.Read method will read the content of the image by a sequence of bytes from the current stream and advances the position within the stream by the number of bytes it read. So myimage contains the image as binary data. Now we have to pass this data into the SqlCommand object, which will insert it into the database table. Display So far, the database in displaying it you need to need to the Image in a GridView with Handler.ashx

article explains the way to insert images into the database. The Image is in the binary data format. Retrieving this data in an ASP.NET web page is fairly easy, but is not as simple. The basic problem is that in order to show an image in an apsx page, add an image tag that links to a separate image file through the src attribute or you put an Image control in your page and specify the ImageUrl.

For example:
<asp:Image ID="Image1" runat="server" ImageUrl="YourImageFilePath" />

Unfortunately, this approach will not work if you need to show image data dynamically. Although you can set the ImageUrl attribute in code, you

have no way to set the image content programmatically. You could first save the data to an image file on the web servers hard drive, but that approach would be dramatically slower, wastes space, and raises the possibility of concurrency errors if multiple requests are being served at the same time and they are all trying to write the same file. In these situations, the solution is to use a separate ASP.NET resource that returns the binary data directly from the database. Here HTTP Handler class comes to center stage. What is Handler?

An ASP.NET HTTP Handler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance. A handler class implements the IHttpHandler interface. For this article demonstration, we are going to display the image in the GridView control along with the data we stored in the table. Here are the steps required to accomplish this: 1. Create a Handler.ashx file to perform image retrieval. This Handler.ashx page will contain only one method called ProcessRequest. This method will return binary data to the incoming request. In this method, we do normal data retrieval process and return only the Image_Content field as bytes of array. The sample code follows
public void ProcessRequest (HttpContext context) { SqlConnection myConnection = new SqlConnection(YourConnectionString); myConnection.Open(); string sql = "Select Image_Content, Image_Type from ImageGallery where Img_Id=@ImageId"; SqlCommand cmd = new SqlCommand(sql, myConnection); cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"]; cmd.Prepare(); SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); context.Response.ContentType = dr["Image_Type"].ToString(); context.Response.BinaryWrite((byte[])dr["Image_Content"]); dr.Close(); myConnection.Close(); }

2. Place a GridView control in your aspx page, with one TemplateField column, add an Image control into the TemplateField's ItemTemplate section. Specify the ImageUrl property as
<asp:TemplateField> <ItemTemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?id=" + Eval("Img_Id") %>' /> </ItemTemplate> </asp:TemplateField>

3. Now we can bind the GridView control to

display all the records in the table as follows


GridView1.DataSource = FetchAllImagesInfo(); GridView1.DataBind();

Before you bind the GridView, you should write the FetchAllImagesInfo method to return all the records with their image data from the table and then you have to load the images into the GridView control. The code for FetchAllImagesInfo is
public DataTable FetchAllImagesInfo()) { string sql = "Select * from ImageGallery"; SqlDataAdapter da = new SqlDataAdapter(sql, "Your Connection String"); DataTable dt = new DataTable(); da.Fill(dt); return dt; }

That's it. When you run your project, you can see the images got loaded into the GridView control. This is a very simple explanation to store images into the data source and to retrieve it back to display in the webpage. You can make the logic even simpler and even elaborate it upto your requirements.

You might also like