Filebytes for multiple fileuploads - asp.net

I have a form with a multiple fileupload on. (You can select multiple files within the same filecontrol
These files I have to upload to an API
If I don't have a multiple, but a single fileupload, I can do
byte[] filedata = FileUploadControl.FileBytes;
String filestring = Convert.ToBase64String(filedata);
If have multiple fileupload, I can use this to iterate over the files:
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
if (uploadfile.ContentLength > 0)
{
Int32 ContentLength = uploadfile.ContentLength;
String ContentType = uploadfile.ContentType;
string filename = uploadfile.FileName;
}
}
But I don't have uploadfile.FileBytes
How can I get the contents of the file to a string?

I got it to work like this:
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
if (uploadfile.ContentLength > 0)
{
...
MemoryStream ms = new MemoryStream(uploadfile.ContentLength);
uploadfile.InputStream.CopyTo(ms);
String filestring = Convert.ToBase64String(ms.ToArray());
...
}
}

Related

Export to Excel function working in localhost but not in published website

I have this code to export my GridViews to Excel, it works in localhost but after deploying it does not work. The error I received upon clicking my export button is Runtime Error.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
String DATA1 = "DATA1";
String DATA2 = "DATA2";
ExportToExcel(app, workbook, DATA_1, DATA1);
workbook.Worksheets["Sheet1"].Delete();
workbook.Worksheets["Sheet2"].Delete();
workbook.Worksheets["Sheet3"].Delete();
ExportToExcel(app, workbook, DATA_2, DATA2);
string FolderPath = ServerName + DirectoryLocation + DirectoryFolder + ExportsFolder;
var filename = #"EXCEL_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";
workbook.SaveAs(FolderPath + filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close();
app.Quit();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.TransmitFile(FolderPath + filename);
Response.Flush();
Response.End();
}
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName)
{
// see the excel sheet behind the program
app.Visible = false;
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
}
I solved my question using EPPLUS, EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx). It does not require excel to be installed on the server machines. thanks.
The codes below is an reference:
protected void ExportToExcel_Click(object sender, EventArgs e)
{
var products = GetProducts();
GridView1.DataSource = products;
GridView1.DataBind();
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Products");
var totalCols = GridView1.Rows[0].Cells.Count;
var totalRows = GridView1.Rows.Count;
var headerRow = GridView1.HeaderRow;
for (var i = 1; i <= totalCols; i++ )
{
workSheet.Cells[1, i].Value = headerRow.Cells[i - 1].Text;
}
for (var j = 1; j <= totalRows; j++ )
{
for (var i = 1; i <= totalCols; i++)
{
var product = products.ElementAt(j-1);
workSheet.Cells[j + 1, i].Value = product.GetType().GetProperty(headerRow.Cells[i - 1].Text).GetValue(product, null);
}
}
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=products.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
'Microsoft.Office.Interop.Excel' means that Microsoft Office Runtime must be installed to make this code work.
Exporting data using Microsoft.Office.Interop.Excel is avoided, since it needs application installation on server, is poorly scalable, and is against MS Office licence conditions.
I suggest other ways, like text-csv exporting that will meet better performance on a server.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
...
StringBuilder sb = new StringBuilder();
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
sb.Append (gridview.Columns[i - 1].HeaderText);
stringBuilder.Append(",");
}
sb.Append(Environment.NewLine);
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
sb.Append (gridview.Rows[i].Cells[j].Text.ToString());
stringBuilder.Append(",");
}
sb.Append(Environment.NewLine);
}
WriteToCSV(sb.ToString();
}
public static void WriteToCSV(string text, string fileName)
{
string attachment = "attachment; filename="+fileName+DateTime.Now.ToString("yy-MM-dd")+".csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv;charset=utf8";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.Write('\uFEFF'); //this is BOM
HttpContext.Current.Response.Write(text);
HttpContext.Current.Response.End();
}
The reason it is failing is you don't have Excel installed. There are other options here (such as converting to CSV file), but if you want to use your code as is, the simplest way is to probably just install Excel on the server !

File Upload to Database for ASP.Net Webpages

Im having some trouble finding a way to Upload a document to the database in varbinary(max) with ASP.Net Webpages 2 and I would also like to download it.
So far what i have is this below which supposed to upload a file to a directory on the website but it isn't doing anything. Any help would be great. Thanks
var fileName = "";
var fileSavePath = "";
int numFiles = Request.Files.Count;
int uploadedCount = 0;
for (int i = 0; i < numFiles; i++)
{
var uploadedFile = Request.Files[i];
if (uploadedFile.ContentLength > 0)
{
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
uploadedCount++;
}
}
message = "File upload complete. Total files uploaded: " +
uploadedCount.ToString();
The following code goes at the top of the page where you have your file upload. Note that you should amend the table and field names according to your database. Also, you should ensure that the form that includes your upload control has the enctype attribute set to multipart/form-data:
#{
int id = 0;
var fileName = "";
var fileMime = "";
if (IsPost) {
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
if(fileName != String.Empty)
{
fileMime = uploadedFile.ContentType;
var fileStream = uploadedFile.InputStream;
var fileLength = uploadedFile.ContentLength;
byte[] fileContent = new byte[fileLength];
fileStream.Read(fileContent, 0, fileLength);
var db = Database.Open("FileUploading");
var sql = "INSERT INTO Files (FileName, FileContent, MimeType) VALUES (#0,#1,#2)";
db.Execute(sql, fileName, fileContent, fileMime);
}
}
}
To display a file from the database, you need a separate "handler" file that contains just this code:
#{
int id = 0;
if(Request["Id"].IsInt()){
id = Request["Id"].AsInt();
var db = Database.Open("FileUploading");
var sql = "Select * From Files Where FileId = #0";
var file = db.QuerySingle(sql, id);
if(file.MimeType.StartsWith("image/")){
Response.AddHeader("content-disposition", "inline; filename=" + file.FileName);
} else {
Response.AddHeader("content-disposition", "attachment; filename=" + file.FileName);
}
Response.ContentType = file.MimeType;
Response.BinaryWrite((byte[])file.FileContent);
}
}
This file is used as the src attribute for an image file or as the URL for a link to a file that should be downloaded such as a PDF or Word file. If you call this handler file "download.cshtml", the link for an image file saved in the database should look like this:
<img src="download.cshtml?Id=#id" alt="" />
where the Id parameter value is the id fo the file in the database. A download link looks like this:
Click Here
All of this has been taken from my article: http://www.mikesdotnetting.com/Article/148/Save-And-Retrieve-Files-From-a-Sql-Server-CE-Database-with-WebMatrix. The only difference between the article which features a SQL Compact database is that the data type for files in SQL CE is image as opposed to varbinary(max) in SQL Server.
based on your code..you are not uploading the image to the database. instead u're saving the image on your folder which is located in your root / UploadedFiles
to store the image in the database..you should use this code..
using (Stream fs = uploadedFile.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string contentType = uploadedFile.PostedFile.ContentType;
SqlParameter[] arParams = new SqlParameter[2];
arParams[0] = new SqlParameter("#ID", SqlDbType.Int);
arParams[0].Value = 1; 'example
arParams[1] = new SqlParameter("#contentType", SqlDbType.Varchar(50));
arParams[1].Value = contentType;
arParams[2] = new SqlParameter("#document", SqlDbType.Varbinary(MAX));
arParams[2].Value = bytes;
SqlHelper.ExecuteNonQuery(SQLConn, CommandType.StoredProcedure, "Upload_Attachment", arParams);
}
}

Send mail with multiple file attachments using HttpFileCollection without saving it first

I want to send email with multiple file attachment.
I use System.Web.Mail.MailMessage, and add all file attachments in HttpFileCollection.
MailMessage msg = new MailMessage();
string body = BodyTextBox.Text;
string smtpServer = "mail.MySite.com";
string userName = "info#Mysite.com";
string password = "***";
int cdoBasic = 1;
int cdoSendUsingPort = 2;
if (userName.Length > 0)
{
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", smtpServer);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", cdoSendUsingPort);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", cdoBasic);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", userName);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password);
}
msg.To = "doc#Mysite.com";
msg.From = "info#Mysite.com";
msg.Subject = "Sent mail";
msg.Body = body;
if (fileUpload.HasFile)
{
int iUploadedCnt = 0;
HttpFileCollection hfc = Request.Files;
for (int i = 0; i <= hfc.Count - 1; i++) // CHECK THE FILE COUNT.
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("Uploaded_Files\\") + Path.GetFileName(hpf.FileName));
msg.Attachments.Add(new MailAttachment(Server.MapPath("Uploaded_Files\\") + Path.GetFileName(hpf.FileName)));
}
}
}
msg.BodyEncoding = System.Text.Encoding.UTF8;
SmtpMail.SmtpServer = smtpServer;
SmtpMail.Send(msg);
It is ok, But i don't want to save file in server, I want send a mail without saving it.
Use the System.Net.Mail.Attachment class, instead of the System.Web.Mail.MailAttachment class, and you can use the overload that accepts a Stream as the first argument:
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
msg.Attachments.Add(new Attachment(hpf.InputStream, Path.GetFileName(hpf.FileName)));
}

Converting HttpFileCollection to byte and stream the data to Image Control in asp.net

HttpFileCollection oHttpFileCollection = e.PostedFiles;
HttpPostedFile oHttpPostedFile = null;
if (e.HasFiles)
{
for (int n = 0; n < e.Count; n++)
{
oHttpPostedFile = oHttpFileCollection[n];
if (oHttpPostedFile.ContentLength <= 0)
continue;
else
oHttpPostedFile.SaveAs(Server.MapPath("Files") + "\\" + System.IO.Path.GetFileName(oHttpPostedFile.FileName));
}
How can I convert HttpFileCollection to byte and read the stream and then display the image to Image Control in asp.net
Thanks
HttpFileCollection oHttpFileCollection = e.PostedFiles;
HttpPostedFile oHttpPostedFile = null;
if (e.HasFiles)
{
for (int n = 0; n < e.Count; n++)
{
oHttpPostedFile = oHttpFileCollection[n];
if (oHttpPostedFile.ContentLength <= 0)
{
continue;
}
else
{
var filename = Path.GetFileName(oHttpPostedFile.FileName);
var path = Path.Combine(Server.MapPath("~/Files/"), filename);
oHttpPostedFile.SaveAs(path);
// Now you could display each image in a dynamically added Image
// control to the page:
Image image = new Image();
image.ImageUrl = "~/Files/" + filename;
// I assume that you have a reference to the current page
// so that you could append image controls to it.
// You could also append the images to a placeholder or a Panel
// on your WebForm
this.Controls.Add(image);
}
}

Multi file upload issue

I used multi file upload to upload file in ASP.Net without issues. But now i want to add more functionality like creating thumbnails while uploading below is my code:
try
{
string _path = "~/photos/realimg/";
string _thumPath = "~/photos/thumbimg/";
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
_path += System.IO.Path.GetFileName(hpf.FileName);
_thumPath += System.IO.Path.GetFileName(hpf.FileName.Insert(0, "thumb_"));
hpf.SaveAs(Server.MapPath(_path));
SavePicPath(_path);
System.Drawing.Image realImg = System.Drawing.Image.FromFile(Server.MapPath(_path));
Int32 rH = realImg.Height;
Int32 rW = realImg.Width;
Int32 fW = 170;
Int32 fH = (Int32)Math.Floor((double)rH * (fW / rW));
System.Drawing.Image thumbimg = realImg.GetThumbnailImage(fW, fH, null, IntPtr.Zero);
thumbimg.Save(Server.MapPath(_thumPath));
SavePicPath(_thumPath);
}
}
}
catch
{
}
Anytime it gets to GetThumbnailImage i get an error "Out of memory" please any correction or what am i doing wrong
Change int values to (float or double). i think here fw/rw returning int value than float or double value.

Resources