In my application user can download a file after clicking a link. Document is PDF/RTF generated in code. I use:
byte[] downloadBytes = some pdf document bytes...
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"attachment; filename=filename.pdf; size=" + downloadBytes.Length.ToString());
response.Flush();
response.BinaryWrite(downloadBytes);
response.Flush();
response.End();
It works OK but is this generally a good way ? Why flush is called two times? I found many different examples and this one works fine but sometimes I got The remote host closed the connection. The error code is 0x80070057
error. I found solution that I should use
if (Response.IsClientConnected)
{
Response.Flush();
Response.End();
}
How the entire code should look like?
Here is the code that I use. It does not call flush at all. I am not sure if it is the right way, but it works for me.
public static void ResponseOpenFileBytes(byte[] File, string ContentType, string SaveAsFileName, HttpResponse response)
{
if (string.IsNullOrEmpty(ContentType))
{
ContentType = "application/octet-stream";
}
response.Clear();
response.AddHeader("content-disposition", "attachment;filename=" + SaveAsFileName);
response.ContentType = ContentType;
response.BinaryWrite(File);
response.End();
}
I don't see why you should call Flush()
two times. One is enough, after calling BinaryWrite()
.
The first call to Flush()
sends the headers to the browser, including Content-Length
, which is still unknown at the time of the call - or simply wrong.
Also, I would avoid calling End()
unless it's absolutely necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With