Sunday, January 22, 2012

how to save image in database in asp.net


Here i will demonstrates how to upload image and then save into Sql data base in ASP.NET.application.For this i have taken a File Upload Control.button and grid view.Before going to insert the Image into Database i am checking the the file upload in empty or not.If it is not empty then go to insertion procedure

Code behind:
protected void btnImgUpload_Click(object sender, EventArgs e)
{
string strImg= txtImgName.Text;
if (ImgFileUpload.PostedFile != null && ImgFileUpload.PostedFile.FileName != "")
{
byte[] strImageSize = new byte[ImgFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadImage = ImgFileUpload.PostedFile;
uploadImage.InputStream.Read(imageSize, 0, (int)ImgFileUpload.PostedFile.ContentLength);

SqlConnection cn=new SqlConnection("Userid=sa;Password=123;Database=employee");

try
{ 
cmd.parameter.clear();
cmd.Parameters.Add("@ImageName", SqlDbType.VarChar).Value = strImg.ToString();;
cmd.Parameters.Add("@Imagesize", SqlDbType.Image,imageSize.Length).Value = strImageSize; 
cn.Open();
cmd = new SqlCommand("SaveImagerecord", cn);
cmd.CommandType = CommandType.StoredProcedure; 
cmd.ExcuteNonQuery();
 
}
catch(exception ex)
{
messageBox.show(ex.message);
}
finally
{
cn.Close();
}
gvimages.DataBind();
}
}
Stored Procedure:
//stored procedure to insert the Images into  in Sqlserver Table
CREATE PROCEDURE SaveImagerecord

(
@ImageName VarChar(100),
@Imagesize byte
)

AS
INSERT INTO Images(ImageName,Imagesize)VALUES (@ImageName,@Imagesize);

1 comment:

Anonymous said...

Thanks for the post!!!

Bel