Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send file in HttpResponse?

Tags:

asp.net

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?

like image 931
jlp Avatar asked May 05 '11 09:05

jlp


2 Answers

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();
}
like image 51
Chris Mullins Avatar answered Nov 16 '22 12:11

Chris Mullins


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.

like image 38
Dario Solera Avatar answered Nov 16 '22 13:11

Dario Solera