I am using this code to download a image i.e. I am storing Image name with extension in database and getting it here.
this code throws no error but doesn't download anything. why ?
try {
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
Update:
i tried this but doesn't work.
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath).CopyTo(m);
m.WriteTo(Response.OutputStream);
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
Create a Stream using following code
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath ).CopyTo(m);
m.WriteTo(Response.OutputStream);
You're on the right track using TransmitFile. Check this line:
Response.ContentType = ContentType;
It looks like you're setting the ContentType to the page's default.
Try specifying it explicitly:
Response.ContentType = "image/jpeg";
Related
I am trying to generate a csv with UTF8 encoding with c#, using ExcelPackage (). Excel is identifying the file as .xlsx and not UTF8. My code:
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("myName");
int y = 1;
foreach (IDictionary<string, string> elemento in losDatos)
{
ws.Cells["A" + y].Value = "+ DisposiciĆ³n de contacto";
ws.Cells["B" + y].Value = "Llamada detallada";
...
...
ws.Cells["AL" + y].Value = "1";
y++;
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
I have tried some changes, only in the Response piece, and now the csv recognizes me, but the characters are strangers:
Response.Clear();
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
Replace
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
with
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".xlsx");
and you are done.
If you want a CSV, use a different package but then do consider adding charset to the Content-Type header. If Open XML is not your thing, then OpenDocument Spreadsheet (.odt, LibreOffice) would be equally better than CSV.
My xlsx file is downloaded but when I open that xlsx file it shows warning as
'We found a problem with some content in'.
Can anyone tell me where I have to fix this? I am using an iFrame to download the file.
using (ClosedXML.Excel.XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Sheet1");
Response.Clear();
Response.Charset = "";
Response.Buffer = true;
Response.BinaryWrite(bytes);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + >Model.reportName + "_" + DateTime.Now.ToString("yyyyMMddHH:mm") + "." + extension);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
I'm trying to have a website export a .xlsm file and I can't seem to find anything that helps. Here's a simple example I'm using to test building a .xlsx file (which works).
#using OfficeOpenXml;
<html>
<body>
<div id="page-wrapper">
#{
// Change file extension to xlsm to test
string fileExtension = "xlsm";
ExcelPackage p = new ExcelPackage();
p.Workbook.Worksheets.Add("Worksheet Name");
int LatestWorksheetNumber = p.Workbook.Worksheets.Count;
ExcelWorksheet ws = p.Workbook.Worksheets[LatestWorksheetNumber];
ws.Cells[1, 1].Value = "Test";
//Generate A File
Byte[] bin = p.GetAsByteArray();
string filename = "filename";
try
{
//Download the file as an attachment
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
string ContentType = "";
if (fileExtension == "xlsx")
{
ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else
{
ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
}
Response.GetType();
Response.ContentType = ContentType;
Response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + fileExtension);
Response.BinaryWrite(bin);
Response.End();
<p>File Created</p>
}
catch (Exception e)
{
<p>#e.Message</p>
}
}
</div>
</body>
</html>
After changing the file extension to .xlsm the file is generated but when I try to open the file in Excel I get an error saying that the extension isn't correct. I thought the only thing I would have to change would be the content type header but that's obviously not the issue. What else am I missing??? Any guidance would be appreciated!
Xiaoy312 nailed the issue! Adding p.Workbook.CreateVBAProject(); before Byte[] bin = p.GetAsByteArray(); solved my issue! Everything else stayed the same but Excel will actually open the files now! Here's my final code for anyone who has the same issue:
#using OfficeOpenXml;
<html>
<body>
<div id="page-wrapper">
#{
// Change file extension to xlsm to test
string FileExtension = "xlsm";
ExcelPackage p = new ExcelPackage();
p.Workbook.Worksheets.Add("Worksheet Name");
int LatestWorksheetNumber = p.Workbook.Worksheets.Count;
ExcelWorksheet ws = p.Workbook.Worksheets[LatestWorksheetNumber];
ws.Cells[1, 1].Value = "Test";
p.Workbook.CreateVBAProject();
//Generate A File
Byte[] bin = p.GetAsByteArray();
string filename = "filename";
try
{
//Download the file as an attachment
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
string ContentType = "";
if (FileExtension == "xlsx")
{
ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else
{
ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
}
Response.GetType();
Response.ContentType = ContentType;
Response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + FileExtension);
Response.BinaryWrite(bin);
Response.End();
<p>File Created</p>
}
catch (Exception e)
{
<p>#e.Message</p>
}
}
</div>
</body>
</html>
I have an error with regards to the subject above, basically I am just downloading a file from its path. My download code is this:
string sFile = Request.QueryString["RFBNumber"].ToString();
string sFile2 = Request.QueryString["FolderName"].ToString();
string sFlag = Request.QueryString["Flag"].ToString();
//CreateRFBReport(sFile, sFile2);
//CreateSingleFile(sFile2, sFile);
if (sFlag == "1") {
sFilename = "RFB_" + sFile + "_COLLATED.PDF";
sGlobalFolderName = sFile2;
sFilePath = # "" + sGlobalFolderName + "\\" + sFilename;
WebClient client = new WebClient();
byte[] buff = client.DownloadData(sFilePath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buff.Length.ToString());
Response.BinaryWrite(buff);
}
if (sFlag == "2") {
sFilename = "SOP_" + sFile + "_COLLATED.PDF";
sGlobalFolderName = sFile2;
sFilePath = # "" + sGlobalFolderName + "\\" + sFilename;
WebClient client = new WebClient();
byte[] buff = client.DownloadData(sFilePath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buff.Length.ToString());
Response.BinaryWrite(buff);
}
I have to refresh the page multiple times before I can download the item, however I am having an error on the line byte[] buff = client.DownloadData(sFilePath);
Can anyone help me please? Been searching a way to solve this issue. Thank you in advance.
I am actually wondering why when I create a zip file, and I download it just after, I can't open it because it's broken ..
This is the code I am actually using .
string url = ((LinkButton)sender).Tag;
var downloadFileName = string.Format(((LinkButton)sender).ID + ".zip");
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C://inetpub//wwwroot//Files//Wireframes//" + url);
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("C://inetpub//wwwroot//Files//Wireframes//" + url, zip.Name);
zip.AddDirectory("C://inetpub//wwwroot//Files//Wireframes//" + url);
zip.Save(downloadFileName);
}
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Also, I am adding directly all the directories with their files inside.
You are not sending the actual data.
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Response.TransmitFile(downloadFileName);
Response.End();