Wednesday, March 3, 2010

C# code for upload image file into database

Database Table

Fields                          Type
img_name                - varchar(50)
img_data                  - image
img_contenttype       -varchar(50)

In form


1.    Add fileupload control
2.    Add button control
3.    Add label control for message display
4.    Write the below code in button onclick event

code
Stream imgstream = FileUpload1.PostedFile.InputStream;
int imglen = FileUpload1.PostedFile.ContentLength;
string imgname = FileUpload1.FileName;
string imgtype = FileUpload1.PostedFile.ContentType;
//create a byte array
byte[] imgdata = new byte[imglen];
//convert Image Stream to a Byte array
int n = imgstream.Read(imgdata, 0, imglen);

SqlConnection scon = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);

(Or)
SqlConnection scon = new SqlConnection("ConnectionString");
string Sql = "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( '" + imgname + "', '" + imgdata + "','" + imgtype + "' )";
SqlCommand cmd = new SqlCommand(Sql, scon);
scon.Open();
int val = cmd.ExecuteNonQuery();
scon.Close();
if (val > 0)
{
Label1.Text = "The Image was saved";
}
else
{
Label1.Text = "An error occurred uploading the image";       
}

0 comments:

Post a Comment