问题
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?
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/4833150/is-there-a-way-to-complete-the-post-back-after-writing-out-a-file-to-the-respons