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...

SQLServer Error: 15404, Could not obtain information about Windows NT group/user Error code 0x5. [SQLSTATE 42000] (ConnIsLoginSysAdmin)

If we encounter this error "SQLServer Error: 15404, Could not obtain information about Windows NT group/user Error code 0x5. [SQLSTATE 42000] (ConnIsLoginSysAdmin)" in SQL Server in which the job fails because of the user account related problem, then we need to take the following steps to make it work: a. Go to SQL Server Agent. b. Then select the job which is giving error and not running successfully. c. Then choose properties and in the General Tab, change the owner to "SA" or any account that has the administrative privileges. The problem will be resolved.

How to Delete Record through Knex.

This post is all about of deleting records through KNEX ORM in Nodejs. The following code shows how to achieve this: knex("depts").where("deptno","50").del() .then(function (count) {     console.log(count); }) .finally(function () {     knex.destroy(); }); The above code deletes a record from a table "Depts" where Deptno = 50. It has a "then" Promise attached that will show how many records were deleted with this command. Also "finally" is the method that will always execute and will close the KNEX connection. Happy Coding !!!