CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Upload image to Sql Server Database in C# and ASP.Net
Submitted By Satheesh Babu B
On 11/17/2008 7:10:14 AM
Tags: asp.net,C#,CodeDigest  

 Upload image to Sql Server Database in C# and ASP.Net

 


Create a table called "Image" with columns ImageID(Identity), ImageName(Varchar(50)) and Image(image) in your Sql Server. We will use FileUpload control for selecting the image from the filesystem, a TextBox for giving a name for the image and a Button control to upload the image once clicked.

 

In the below code snippet, the uploaded image from the FileUpload control is read as byte array which is then inserted to the database table called Image.
 
protected void btnUpload_Click(object sender, EventArgs e)
    {
        Stream imgStream = fuImage.PostedFile.InputStream;
        int imgLen = fuImage.PostedFile.ContentLength;
        string imgName = txtImageName.Text;
        byte[] imgBinaryData = new byte[imgLen];
        int n = imgStream.Read(imgBinaryData,0,imgLen);
 
        //use the web.config to store the connection string
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
        SqlCommand command = new SqlCommand("INSERT INTO Image (imagename,image) VALUES ( @img_name, @img_data)", connection);
 
        SqlParameter param0 = new SqlParameter("@img_name", SqlDbType.VarChar, 50);
        param0.Value = imgName;
        command.Parameters.Add(param0);
 
        SqlParameter param1 = new SqlParameter("@img_data", SqlDbType.Image);
        param1.Value = imgBinaryData;
        command.Parameters.Add(param1);
 
        connection.Open();
        int numRowsAffected = command.ExecuteNonQuery();
        connection.Close();
    }

 

In the above code, fuImage is the id of the FileUpload control from which we are trying to upload the image.
 
Configure the connection string in the web.config file corresponding to the sqlserver you use.

Inlcude System.Data.SqlClient, System.IO and System.Configurations namespace for the above code to work.

 

Happy Coding!!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..