将文件写到响应后,有没有办法完成回发? [英] Is there a way to complete the post back after writing out a file to the Response?
问题描述
我有一个按钮,当单击该按钮时,将生成PDF并将其写到响应中。
I have a button that when clicked, will generate a PDF and write it out to the response.
这是代码的基本结构:
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.
如果我在 file.Transmit
之上抛出异常,错误处理将正常工作,并且我会看到消息显示在我的浏览器。但是,如果 file.Transmit
之后存在异常,则什么也不会发生。用户保存/打开pdf,并且页面不会重新加载。
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?
推荐答案
听起来您正在尝试使响应包含两部分:页面和 PDF。你不能那样做。通常,下载页面在到达页面后会作为一个单独的请求开始下载(我相信是通过JavaScript),并带有直接链接,以防JavaScript无法正常工作。
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.
任何一个HTTP请求只能有一个响应。
Any one HTTP request can only have one response.
这篇关于将文件写到响应后,有没有办法完成回发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!