Thursday, October 28, 2010

upload file to a database

Following is code to read a file from html Input and convert it into byte[]

byte[] imgBinaryData = null;

try
{
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData, 0, imgLen);
imgStream .Dispose ();
}
catch (Exception)
{


}


Following is the code to insert in DB

string cmdtext1 = "INSERT INTO [Info]([ID] ,[Picture],[afterpic])  values(1,@pic,@aftpic)";
SqlConnection scn = new SqlConnection(AppContext.ConnectionString);
SqlCommand scmd = new SqlCommand(cmdtext1, scn);
SqlParameter param1 = new SqlParameter("@pic", SqlDbType.Image);
SqlParameter param2 = new SqlParameter("@aftpic", SqlDbType.Image);
param1.Value = imgBinaryData;
param2.Value = imgBinaryData1;
scmd.Parameters.Add(param1);
scmd.Parameters.Add(param2);
scn.Open();
scmd.ExecuteNonQuery();
scn.Close();
imgBinaryData=null;;
imgBinaryData1=null;


Thanks,
Suman

No comments:

Post a Comment