我有一个允许从服务器下载文件的Web应用程序。文档可能是 Office 文件 (.docx、pptx、.xslx) 或 PDF。
逻辑非常简单:从客户端单击时,将调用 Web 服务并调用传递所需参数的 aspx 页 (Print.aspx)。打印页调用 Web 服务来检索选定的文档二进制文件,并将其写入响应中:
protected void Page_Load(object sender, EventArgs e)
{
string fileName = Request.QueryString["fname"];
if (string.IsNullOrEmpty(documentID) == false)
{
byte[] document = GetPhysicalFile(documentID); //Get the binaries
showDownloadedDoc(document, fileName);
}
}
private void showDownloadedDoc(byte[] document, string fileName)
{
Response.Clear();
Response.ContentType = contentType;
Response.AppendHeader("content-disposition", string.Format("attachment; filename="{0}"", fileName));
Response.BufferOutput = false;
Response.BinaryWrite(document);
Response.Close();
}
PDF 文档在"打印.aspx"页中打开,并且 aspx 页仅加载一次。对于 Office 文件,Page_Load() 方法被调用 3 次。
第一次打开"打开/保存"文档的对话框后,如果单击"打开"ic,则调用Page_Load两次,然后文档最终在MS Word中出现,例如。
有没有办法防止打开这些文档时加载多个页面?我想避免将文件保存在服务器端并重定向到该 URL,因为将为每个访问创建一个文件。
一个带有 GenericHandler 的示例
public void ProcessRequest(HttpContext context)
{
string filePath; // get from somewhere
string contentType; // get from somewhere
FileInfo fileInfo = new FileInfo(filePath);
context.Response.Clear();
context.Response.ContentType = contentType;
context.Response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFilename(filePath));
context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
context.Response.TransmitFile(filePath);
}
我怀疑您使用单击进行回发,然后避免让响应重播以通知ViewState命令已完成并更新页面上的内容。
因此,在下一次单击时,旧命令仍在等待并按页面重新发送,现在您有两个命令 - 两个调用,但随后您再次不让返回以再次更新视图状态,并且页面认为必须再次等待。
这在每次下一次调用时都会继续,后面的代码实际上是尝试运行所有前一个。
对此的解决方案是直接链接到处理程序,而不是使用 ajax 从代码后面调用它。