4

I have a button that when clicked, will generate a PDF and write it out to the response.

This is the basic structure of the code:

try
{
    using(Stream stream = generatePdf())
    {
       var file = createFile(stream);
       file.Transmit(HttpContext.Current.Response);
    }
}
catch (Exception ex)
{
    // Handle exception
    // Display Error Message
}

The transmit method contains the following code:

response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", filename));
response.AddHeader("Content-Length", bytes.Length.ToString());
response.ContentType = "application/octet-stream";
response.BinaryWrite(bytes);

Downloading the file works fine, except that it doesn't complete the postback.

If I were to throw an exception above file.Transmit, the error handling would work properly and I would see the message get displayed in my browser. However, if there is an exception after the file.Transmit then nothing happens. The user saves/opens the pdf and the page does not reload.

How can I make it so that the postback always completes, that way I can display an appropriate message to the user?

Brandon
  • 68,708
  • 30
  • 194
  • 223

2 Answers2

4

It sounds like you're trying to make the response contain two parts: the page and the PDF. You can't do that. Typically download pages start a download as a separate request when you've gone to them (via JavaScript, I believe), with a direct link just in case the JavaScript doesn't work.

Any one HTTP request can only have one response.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Response.End() literally ends the entire response.

There are two methods that I employ when I use it:

1) Always make sure it's the final required point in the postback.

2) (and the only way to use AJAX for file calls) Make a small page in an iframe solely for the purpose of sending files and call a refresh on the frame... the response.end will just end the response from that frame, not the entire postback.

EDIT: Here's my question thread on the same topic Using Response.TransmitFile for physical file not working

Community
  • 1
  • 1
Matthew
  • 10,244
  • 5
  • 49
  • 104