Search This Blog

Friday, April 16, 2010

How to save image as a byte array in database through ASP.NET


First we will give the link of the image in FileUpload control.
Then we will retrieve the image content type (.txt, .jpeg, .png etc) and image length, as follows
    HttpPostedFile selectedFile = FileUpload1.PostedFile;
    int imageLength = selectedFile.ContentLength;
    string imageType = selectedFile.ContentType;
 
Then we will create a byte array of length - imageLength and copy the contents as shown below:
 
Byte[] imageArray = new byte[imageLength];
selectedFile.InputStream.Read(imageArray, 0, imageLength);

After that its simple....just create a database connection and send the byte array as a parameter. make sure that in your database (MS SQL) the data type of image is set to "image".

Full Code

///
/// To save the image into database
///
///

///

protected void Button2_Click(object sender, EventArgs e)
{
HttpPostedFile selectedFile = FileUpload1.PostedFile;
int imageLength = selectedFile.ContentLength;
string imageType = selectedFile.ContentType;

Byte[] imageArray = new byte[imageLength];
selectedFile.InputStream.Read(imageArray , 0, imageLength);
con.Open();
SqlCommand com2 = new SqlCommand("Update ABC set Image=@image where ID=@ID", con);
SqlParameter param = new SqlParameter("@image", SqlDbType.Image);
param.Value = imageArray;

SqlParameter param2 = new SqlParameter("@ID", SqlDbType.NVarChar);
param2.Value = txtID.Text;
com2.Parameters.Add(param);
com2.Parameters.Add(param2);
com2.ExecuteNonQuery();

con.Close();

}

No comments:

Post a Comment