Wednesday, December 29, 2010

Multiple file upload in asp.net

This code show how to upload multiple file and save to database using asp.net and c#.
 HttpFileCollection hFileCollection = HttpContext.Current.Request.Files;  
for (int i = 0; i <= hFileCollection.Count; i++)
{
HttpPostedFile hPostedFile = hFileCollection[i];
if (hPostedFile.ContentLength > 0)
{
Stream fs = hFileCollection[i].InputStream;
int ImgLength = hFileCollection[i].ContentLength;
string contenttype = hFileCollection[i].ContentType;
string filePath = Path.GetFullPath(hFileCollection[i].FileName);
string filename = Path.GetFileName(filePath);
string extension = Path.GetExtension(hFileCollection[i].FileName).ToLower();
byte[] BinaryData = new byte[ImgLength];
int n = fs.Read(BinaryData, 0, ImgLength);
int DrawingID = objbztDrawingMasterBLL.CreateDrawingMaster(objbztDrawingMasterCls);
objbztDrawingMasterCls.DfileName = filename;
objbztDrawingMasterCls.FileConetentType = contenttype;
objbztDrawingMasterCls.FileData = BinaryData;
if (extension == ".doc" || extension == ".docx" || extension == ".xls" || extension == ".xlsx" || extension == ".jpg" || extension == ".png" || extension == ".gif" || extension == ".pdf")
{
string cmdstr = "INSERT INTO tblDtFiles(DID,DFileName,FileConetentType,FileData) VALUES(" + DID + "," + Convert.ToString(filename) + "," + Convert.ToString(contenttype) + "," + BinaryData + ")";
SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, cmdstr);
}
else
{
msg.Text = "Uploaded file should be doc/xls/jpg/png/gif/pdf...!";
}
}
}


Thanks & Regards
Santosh Singh