Google Chrome Not Display PDF from asp.net Page - asp.net

I want to display a pdf file on an .aspx page with a button. The codes is like that:
string yol = e.CommandArgument.ToString();
string path = Server.MapPath("~/Raporlar/2021/" + yol.Trim());
WebClient User = new WebClient();
Byte[] s = User.DownloadData(path);
System.IO.MemoryStream ms = new System.IO.MemoryStream(s);
if (ms != null && ms.Length > 1)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Charset = "UTF-8";
Response.Buffer = true;
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.AddHeader("Content-Disposition", "inline; filename=\"" + yol + "\"");
Response.AddHeader("Expires", "0");
Response.AddHeader("Pragma", "cache");
Response.AddHeader("Cache - Control", "private");
Response.ContentType = "application/pdf";
Response.BinaryWrite(ms.ToArray());
Response.Flush();
try { Response.End();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
catch { }
}
The codes works on Firefox, Edge. But it is not work on Google Chrome. What could be problem ? Can you help me ?

Related

Returning a downloadable file using a stream in asp.net web forms

In asp.net MVC I can do something like the following which will open a stream:
Stream strm1 = GenerateReport(Id);
return File(strm1,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Report_" + reportId.ToString() + ".xlsx");
Notice how I am passing strm1 which is a stream. I can then name it Report_+ ...xlsx like the example above shows.
Is there a similar way to do this with asp.net web forms using c#.
You can use TransmitFile or WriteFile if the file is in your website folder.
string fileName = string.Format("Report_{0}.xlsx", reportId);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename={0}", fileName));
Response.TransmitFile(fileName);
Response.End();
Stream
If your data is already in Memory, you want this method which writes the response in chunks.
Stream stm1 = GenerateReport(Id);
Int16 bufferSize = 1024;
byte[] buffer = new byte[bufferSize + 1];
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename=\"Report_{0}.xlsx\";", reportId));
Response.BufferOutput = false;
int count = stm1.Read(buffer, 0, bufferSize);
while (count > 0)
{
Response.OutputStream.Write(buffer, 0, count);
count = stm1.Read(buffer, 0, bufferSize);
}
I use this extension to send a stream as a downloadable file:
public static class ToDownloadExtention
{
public static void ToDownload(this Stream stream, string fileName, HttpResponse response)
{
response.Clear();
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
stream.CopyTo(response.OutputStream);
response.End();
}
}
And the usage is:
var stream = new MemoryStream();
stream.ToDownload("someFileName.ext",Response);
Or if you have a stream ready to be written, simply copy it to response stream:
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename={your file name}");
Response.OutputStream.Write(stream, 0, stream.length);
Response.End();
Added same code just for visibility

ASP.net download file Using HttpContext.Current.Response.TransmitFile in ASP.NET

public void Downloadfile(string sFileName, string sFilePath)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
String Header = "Attachment; Filename=" + sFileName;
HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
HttpContext.Current.Response.AppendHeader("Cache-Control", "no-cache");
System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
HttpContext.Current.Response.TransmitFile(Dfile.FullName);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
I have a download button, the click will return the call and download the corresponding file download, but sometimes file returns is detailt.aspx file. I do not understand what is happening.
I need help. Thanks a lot
This has worked for me with out issue for a while now.
public void Downloadfile(string sFileName, string sFilePath)
{
var file = new System.IO.FileInfo(sFilePath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + sFileName);
Response.AddHeader("Content-Length", file.Length.ToString(CultureInfo.InvariantCulture));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}

Send ExcelPackage file to user

I want to build ExcelPackage file on server side and than send allow user to download it.
Here is my code for file creating:
private byte[] ExcelFileCreate()
{
using (var excelPackage = new ExcelPackage())
{
excelPackage.Workbook.Properties.Author = User.Identity.Name;
excelPackage.Workbook.Properties.Title = "Skybot";
excelPackage.Workbook.Properties.Company = "Dataminds";
excelPackage.Workbook.Worksheets.Add("Selected unit folder");
var excelWorksheet = excelPackage.Workbook.Worksheets[1];
excelWorksheet.Name = "Selected unit folder";
int rowIndex = 1;
int columnIndex = 1;
do
{
var cell = excelWorksheet.Cells[rowIndex, columnIndex];
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.LightGray);
columnIndex++;
} while (columnIndex != 4);
excelWorksheet.Cells[1, 1].Value = "action cell";
excelWorksheet.Cells[1, 2].Value = "time cell";
excelWorksheet.Cells[1, 3].Value = "processor cell";
excelWorksheet.Cells[2, 1].Value = "action cell";
excelWorksheet.Cells[2, 2].Value = "time cell";
excelWorksheet.Cells[2, 3].Value = "processor cell";
return excelPackage.GetAsByteArray();
}
}
And send it you user:
variant 1:
private void FileTransfer(byte[] fileBytes)
{
//Clear the response
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
//Add the header & other information
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.AppendHeader("Pragma", "cache");
Response.AppendHeader("Expires", "60");
Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=\"ExcelReport.xlsx\"; " +
"size=" + fileBytes.Length.ToString() + "; " +
"creation-date=" + DateTime.Now.ToString("R") + "; " +
"modification-date=" + DateTime.Now.ToString("R") + "; " +
"read-date=" + DateTime.Now.ToString("R"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Write it back to the client
Response.BinaryWrite(fileBytes);
Response.End();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment;filename=test.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
}
variant 2:
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment;filename=test.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
variant 3:
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileBytes));
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.BinaryWrite(fileBytes);
Response.End();
And none of them works.
There is no pop-up window with suggestion to store/open file.
Event handler that should make it works:
protected void TreeViewUnit_OnContextMenuItemClick(object sender,
RadTreeViewContextMenuEventArgs eventArgs)
{
FileTransfer(ExcelFileCreate());
}
Any ideas what is wrong?
Try
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelReport.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
It works for me as shown here.

How can I output to a webform before I clear a response?

I have a Webform where a user clicks a button and an Excel file is generated.
This is achieved by this code:
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=export.txt");
Response.ContentType = "text/csv";
Response.WriteFile(FILENAME);
Response.End();
I would like to add to the Response so when the user closes Excel, they can see a message on the Webform.But you can't do this in the code above.
Response.Write("Excel generated!"); ************ does not work as response will be cleared!
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=donman_export.txt");
Response.ContentType = "text/csv";
Response.WriteFile(FILENAME);
Response.End();
How can I do this?
Response.Write("Excel generated!"); ************ does not work
Response.Flush();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=donman_export.txt");
Response.ContentType = "text/csv";
Response.WriteFile(FILENAME);
Response.End();
Code below is doing exactly what have you asked.
It renders additional HTML tags, so download starts after message was shown to user:
protected void Page_Load(object sender, EventArgs e)
{
var currentUrl = Request.Url.OriginalString;
var currentQuery = Request.Url.Query;
var download = new
{
FilePath = "~/test.csv",
FileName = "test.csv",
FileMime = "text/csv",
Message = "Excel generated!",
QueryParam = "direct-download",
Delay = 2 // seconds
};
var hasQueryParams = currentQuery.Length > 0;
var isDownloadUrl = hasQueryParams && currentQuery.IndexOf( download.QueryParam ) >= 0;
if( isDownloadUrl )
{
// Prepare..
Response.ContentType = download.FileMime;
Response.Clear();
Response.BufferOutput = true;
// Transfer..
Response.AddHeader("content-disposition", "attachment; filename=" + download.FileName);
Response.WriteFile(download.FilePath);
// Done..
// Instead of Response.Close()
// http://stackoverflow.com/q/4583201/2361743
Response.Flush();
Context.ApplicationInstance.CompleteRequest();
return;
}
// Meta-Refresh Tag has to be in <HEAD> section, but not all browsers follow this restriction.
// IFRAME has to work fine. It is wrapped into <DIV> to be not visible in old browsers.
const string tagToStartManual = "<A href='{0}'>{1}</A>";
const string tagToStartAfterDelay = "<META HTTP-EQUIV='REFRESH' CONTENT='{1};URL={0}'>";
const string tagToStartImmediately = "<DIV STYLE='{1}'><IFRAME SRC='{0}'></IFRAME></DIV>";
const string cssToHideFrame = "width:1px;height:1px;opacity:0.1;overflow:hidden";
// Show your message..
// And add HTML Tags which would start download:
Response.Write(download.Message);
var downloadUrl = currentUrl + (hasQueryParams ? "&" : "?") + download.QueryParam;
// You don't have to use all 3 methods...
Response.Write( String.Format( tagToStartManual, downloadUrl, download.FileName));
Response.Write( String.Format( tagToStartAfterDelay, downloadUrl, download.Delay) );
Response.Write( String.Format( tagToStartImmediately, downloadUrl, cssToHideFrame) );
// Done.
// Waiting for actual download request...
}

C# Asp Net Problem with download in Chrome 12

I have a problem in my project.
I have some code for downloading content as: .doc, .zip etc
It was working fine until chrome update for version 12, after that the browser shows an error message: "Download Interrupted".
I already tested in other browsers (Chrome 11, FF and IE8) and everything works fine.
An code sample is:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AppendHeader("Content-Type", "application/msword");
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" + filename + ".doc");
HttpContext.Current.Response.AppendHeader("Content-Transfer-Encoding", "binary");
HttpContext.Current.Response.Write(strBody);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
Someone know what can be happening or how I can fix that?
Ps. Sorry my english, I'm brazilian :)
According to an answer in this forum adding Response.End() solved the issue.
In your case, it would be
HttpContext.Current.Response.Write(strBody);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
HttpContext.Current.Response.Close();
I am getting my binary data from sql server database with this code and it is working in all browser;
DataTable table = SiteFileAccess.GetDataByFileID(fileId);
byte[] b = (byte[])table.Rows[0]["FileData"];
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + table.Rows[0]["FileName"].ToString());
Response.AddHeader("Content-Length", b.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(b);
Response.Flush();
Response.End();
See the above code and fix it according to your need. Let me know If you need further information
string applicationName = Session["ApplicationName_UtilityDetail"].ToString();
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(Session["DownloadLink_UtilityDetail"].ToString());
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
int bufferSize = 1;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Disposition:", "attachment; filename=" + applicationName + ".zip");
Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString());
Response.ContentType = "application/download";
byte[] byteBuffer = new byte[bufferSize + 1];
MemoryStream memStrm = new MemoryStream(byteBuffer, true);
Stream strm = objRequest.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (strm.Read(byteBuffer, 0, byteBuffer.Length) > 0)
{
Response.BinaryWrite(memStrm.ToArray());
Response.Flush();
}
Response.Close();
Response.End();
memStrm.Close();
memStrm.Dispose();
strm.Dispose();
Try this:
Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename=yourExcelFileName.xlsx;");
Response.BinaryWrite(yourByteArray);
Response.End();

Resources