German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Loading Images into SQL Server with C#

Written by omerkamal on Dec 13, 2006
Uploading Images to the web server and saving them to the MS SQL Database

Introducation:

As Web sites become larger, they need a better method of storage—for both performance and administrative reasons. If the web site is busy accessing pictures from the hard drive or logical drive, your server becomes less responsive due to increased disk activity.As these sites become larger, they need a better method of storage—for both performance and administrative reasons. If the web site is busy accessing pictures from the hard drive or logical drive, your server becomes less responsive due to increased disk activity. Here we will see how to uplaod Iamges and save them in the database

Explanation:

AS a First step we will create Our UploadImage.aspx File;

1 <%@ Page language="c#" Src="UploadImage.aspx.cs" Inherits="DBImages.UploadImage" %>
2
3
4
5
6

Upload your Image


7 Enter A Friendly Name
8
9
Select File To Upload:
10
11
12
13
14

 

Now let us see what is happning in the code;

 

Line 1 loads our code-behind script, called UploadImage.aspx.cs (given below).

 

Line 5 uses the "multipart/form-data" encoding type for the

tag, telling the browser that a large amount of binary (image) data will be returned by the form.

 

Line 8 uses the .NET RequiredFieldValidator web control. It requires the user to enter a friendly name for the image. If the user attempts to leave this field blank, the script will tell the user that a friendly name is required. Depending on what you're using the script to do, you may not even need the information in this field; it simply provides a reference to the images in a more friendly context, such as for an image library or picture album.

 

Line 10 uses the HtmlInputFile control. This control is part of the HTML controls library for .NET and is basically a fancy text box control that contains a Browse button; it knows that the value it will receive is a binary file.

 

Line 11 is the Button web control, which calls a function named UploadBTn_Click when the button for the control is clicked.

The Code-Behind (.cs) Script;

1 using System;
2 using System.Configuration;
3 using System.Data;
4 using System.Data.SqlClient;
5 using System.Web;
6 using System.IO;
7 using System.Web.SessionState;
8 using System.Web.UI;
9 using System.Web.UI.WebControls;
10 using System.Web.UI.HtmlControls;
11 namespace DBImages
12 {
13 public class UploadImage : System.Web.UI.Page
14 {
15 protected System.Web.UI.WebControls.Button UploadBtn;
16 protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
17 protected System.Web.UI.HtmlControls.HtmlInputText txtImgName;
18 protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;
19 public UploadImage() { }
20 private void Page_Load(object sender, System.EventArgs e){ }
21 public void UploadBtn_Click(object sender, System.EventArgs e)
22 {
23 if (Page.IsValid) //save the image
24 {
25 Stream imgStream = UploadFile.PostedFile.InputStream;
26 int imgLen = UploadFile.PostedFile.ContentLength;
27 string imgContentType = UploadFile.PostedFile.ContentType;
28 string imgName = txtImgName.Value;
29 byte[] imgBinaryData = new byte[imgLen];
30 int n = imgStream.Read(imgBinaryData,0,imgLen);
31 String idis = Request.QueryString["id"];
32 int busid = System.Convert.ToInt32(idis);
33 int RowsAffected = SaveToDB( imgName, imgBinaryData,imgContentType, busid);
34 if ( RowsAffected>0 )
35 {
36 Response.Write("
The Image was saved");
37 }
38 else
39 {
40 Response.Write("
An error occurred uploading the image");
41 }
42 }
43 }
44 private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype, int busid)
45 {
46 //use the web.config to store the connection string
47 SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
48 SqlCommand command = new SqlCommand( "INSERT INTO Image (img_name,img_data,img_contenttype,business_id) VALUES ( @img_name, @img_data,@img_contenttype,@img_busid)", connection );
49 SqlParameter param0 = new SqlParameter( "@img_name", SqlDbType.VarChar,50 );
50 param0.Value = imgName;
51 command.Parameters.Add( param0 );
52 SqlParameter param1 = new SqlParameter( "@img_data", SqlDbType.Image );
53 param1.Value = imgbin;
54 command.Parameters.Add( param1 );
55 SqlParameter param2 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50);
56 param2.Value = imgcontenttype;
57 command.Parameters.Add( param2 );
58 SqlParameter param3 = new SqlParameter( "@img_busid", SqlDbType.Int,4 );
59 param3.Value = busid;
60 command.Parameters.Add( param3 );
61 connection.Open();
62 int numRowsAffected = command.ExecuteNonQuery();
63 connection.Close();
64 return numRowsAffected;
65 }
66 }
67 }

 

Where DSN is our Connection string to the MS SQL Database. You noticed that our lives got easy with the usage of Parameters.

Visitors/Readers Comments



Ho how do u display the image?

Comments By:briiiin

at: 28/02/2007 20:34:59 UTC

Comments By:Kamal

at: 18/04/2007 06:30:44 UTC

Dear Kamal,

I read your article on storing images in SQL Server, which is very interesting and very helpful.

I have been working on SQL Server with ASP.NET (C#.NET) for my project work in India for sometime now. I had requirement where I have been storing the files (.pdf, doc, ppt, etc) in the image field in SQL Server database (similar to storing images) in binary format (as stored in SQL Server). I have been searching for information regarding the storage space required for storing the image data in SQL Server, whether it reduces/increases, how much does it reduce/increase??? Unfortunately, there are many articles in web taking about storing/not storing images in SQL Server, but no one answers this query. It would be really helpful, if you can throw some light on this for me.

At anytime, you can reach me on

Regards

Comments By:Keerthi

at: 06/09/2007 07:48:55 UTC
As it turns out, MS is not going to support the "image" datatype in the next version of SQL server. I can understand it because there were severe problems with the log file because of the image datatype (same goes for text, ntext).
I am currently looking for code to insert image data into a "varbinary" column instead. Any ideas how to do this?
Cheers,
Jonas

Comments By:Jonas

at: 16/11/2007 14:24:06 UTC

Hi,

see the following topic for this problem.

http://www.vbdotnetheaven.com/UploadFile/scottlysle/ImageToSqlServer11242006025136AM/ImageToSqlServer.aspx

Regards!

aamir

http://www.mobilescollection.com

http://www.islamic-wallpapers.com

 

Comments By:aamir

at: 28/01/2008 07:51:15 UTC

sir

thank u for providing the codes and u explained briefly why cant u place the outpu t image its very helpful for new fresher developers by seeing they can gain more knowledge.

 

                                                             thank u

Comments By:santhiswaroop

at: 06/02/2008 23:29:42 UTC
can u ssay me how to convert image into binary data and then insert it directly via sql query i mean from sql query pane itself

Comments By:david

at: 10/02/2008 20:28:00 UTC
I would like to know how to UPDATE the image. In my database I have  .e.g pictures of homes description size etc. I have integrated this with frontpage and everything works fine, I  upload the image the  have the web redirect to  database wiz editor and enter the rest of the fields.. I know how to update the rest of fields of course BUT how do I  replace the image ..

Comments By:Gary

at: 08/03/2008 07:56:09 UTC
Totally wate

Comments By:wasteland

at: 14/05/2008 04:39:25 UTC
Hi,
I read your article on storing images in SQL Server, which is very interesting and very helpful.
                     Thanks.
Regards
Vijay.

Comments By:Vijay

at: 31/05/2008 00:59:29 UTC
hi omerkamal,

nice article to understand how to store image in to sql database.. it helped me a lot..

thanks.. keep writing such informative notes..

sandeep ramani
(http://ramanisandeep.wordpress.com)

Comments By:Sandeep Ramani

at: 04/12/2008 06:34:37 UTC



Add your Comments

Name:
 
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)