Skip to main content

Storing Images in SQL Server Image Datatype in ASP.NET

How to Store Images in SQL Server from an ASP.NET Page


Normally there is a requirement in the dynamic web sites where the user uploads an image for a specific purpose like profile, product image etc. and it has to be saved in the database. This article discusses the step by step process of storing the image chosen in the ASP.NET Page into SQL Server Database. For this I have taken a small table called as “MyPhoto” which contains two fields having following details:

1. PhotoID                 Numeric                     Identity Column


2. Photo                     Image

The image will be stored in the Photo Field which is of type Image and later on can be retrieved with the help of some another process which I will discuss in another post.

Step 1. Create an interface in ASP.NET Page for the UI. I have created a same and giving a snapshot for the same.








Step 2. Write down the code in the code behind of button having label “Upload Photo” :

protected void Button1_Click(object sender, EventArgs e)

{
        if (FileUpload1.HasFile)
       {

                    String vFileName = FileUpload1.PostedFile.FileName;
                    String vCompletedFileName = Server.MapPath("~/Att/" + vFileName);
                    FileUpload1.SaveAs(vCompletedFileName);
                    FileStream fs=new FileStream(Server.MapPath("~/Att/"+ vFileName),FileMode.Open);
                    byte[] img = new byte[fs.Length];
                    fs.Read(img, 0, (int)fs.Length);
                    fs.Close();
                    SqlConnection vConn = new SqlConnection("server=localhost; database = Rohit; user id=sa; pwd=xxxxxx);

                    vConn.Open();
                    String vQuery = "Insert into MyPhoto (Photo) values (@image)";
                    SqlParameter vParameter = new SqlParameter("@Image",SqlDbType.Image, img.Length);
                    vParameter.Value = img;
                    SqlCommand vComm = new SqlCommand(vQuery, vConn);
                    vComm.Parameters.Add(vParameter);
                    vComm.ExecuteNonQuery();
                    Label1.Text="Record Saved in database";
                    vConn.Close();
                    File.Delete(Server.MapPath("~/Att/"+vFileName));
        }
}
I have used an “Att” folder under the WebSite Folder for temporary copying of the image and then storing in the database.

In the above code the following points are to be noted:


1. Opened the database connection first.


2. Used a SQL Command to create a command for insert statement and also used a SQL Parameter.


3. This parameter is for the image. We have to specify the datatype, size of the image etc.


4. Because the image is stored in the form of Image, we must use the bytes format with the help of FileStream to actually store bytes in the image field.


5. And at last the insert statement is executed in the SQL Server and stores the bytes in the image field.

Hope this helps in your development work. I will come with another article that introduces the concept of Generic Handler in ASP.NET

Comments

Unknown said…
While connecting to sql server 2005 database engine i provide my computer name as server it doesnot connect me and following error message is popped up:

login failed for user 'CHANCHAL-PC\Chanchal'
microsoft error 18456
However while installation i have enabled windows authentication.
I also checked services from administrative tools

and i found that MSSQLSERVER was started and started automatically
still i am not able to connect my database engine .
however evrything works fine for other services such as Integration services,Analysis services and all.

I checked it on internet but found no solution some of them have suggested to install service pack3 which i had already done.

Please help me out.
Rohit said…
Make sure that you have mixed authentication mode in the SQL Server and use the same, while coding this.

Popular posts from this blog

How to use QueryExtenderControl in ASP.NET with LINQ

Queryextender control is a control that helps in doing actions like filtration, searching, sorting etc. on the LINQ Data source with few steps. In fact we don’t have to write any code with this. Screenshot given below is just an example that can easily be achieved through this control. In the above screenshot, we can see that there is a GridView Control that has been binded to a LINQData Source Control. And we have a DropDownlistBox that is also binded to another LINQData Source Control and displaying only grouped jobs. The GridView display all the employees who are matching the Job Parameter. This is done through QueryExtender Control. Also we can search for any name in the employee name's through Query Extender control. The code in the HTML goes like: < form id ="form1" runat ="server">     < div >         Select Job: < asp : DropDownList ID ="Job" runat ="server" DataSourceID ="LinqDataSource2&

Using GUID or UniqueIdentifiers in SQL Server

In order to differentiate between two rows, we normally use primary keys or identity values which may be same across two tables. In order to overcome this problem we can use a special type named "GUID" . Its a hexadecimal number (Base 16) and the advantage is  that they are unique across all databases and tables.  In SQL Server the same concept is implemented through UNIQUEIDENTIFIER  data type. In order to generate a new value, we use the NEWID() function. For e.g.  a. Creating a table that uses the UNIQUEIDENTIFIER datatype Create table Test ( Empno uniqueidentifier, Ename varchar(20) ) b. Inserting rows in the tables with the use of NEWID() function insert into Test values (newId(),'ABC') insert into Test values (newid(),'XYZ') insert into test values (newid(),'MNO') c. Selecting the rows from the table. Select * from test  Empno                                                                     Ename 6B2CF0E5-DC2E-4E

How to check the status of CAPS / NUMLOCK status in C#.NET

There are two types of codes available in C#.NET for checking the status of CAPS Lock and NUM Lock. a. Unmanaged Code : The code written in conventional languages like C, C++, VC++ etc. This kind of code can be called in the Managed Environment like .NET, JRE etc. [ DllImport ( "user32.dll" , CharSet = CharSet .Auto, ExactSpelling = true , CallingConvention = CallingConvention .Winapi)] public static extern short GetKeyState( int keyCode); bool CapsLock = ((( ushort )GetKeyState(0x14)) & 0xffff) != 0; bool NumLock = ((( ushort )GetKeyState(0x90)) & 0xffff) != 0; bool ScrollLock = ((( ushort )GetKeyState(0x91)) & 0xffff) != 0; MessageBox .Show( "Caps Lock is on: " + CapsLock.ToString()); MessageBox .Show( "Num Lock is on: " + NumLock.ToString()); MessageBox .Show( "Scroll Lock is on: " + ScrollLock.ToString()); b. Managed Code: Code which is managed by the Runtime environment. This type of code is basically a wr