asp.net - 下载 Office 文件会导致 aspx 页面在打开文件之前重新加载 3 次

标签 asp.net ms-office download

我有一个网络应用程序,允许从服务器下载文件。文档可能是 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 文档在 Print.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);
}

关于asp.net - 下载 Office 文件会导致 aspx 页面在打开文件之前重新加载 3 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10245342/

相关文章:

vb.net - SaveAs2 For Word 2010 无法与装有 Word 2007 的客户端 PC 配合使用

excel - 宏每分钟运行一次,但我希望特定的子程序每 45 分钟运行一次

c# - Microsoft Office Access 数据库引擎找不到对象

ios - urlsession,如何获取多个文件下载的总体进度

适用于 Windows 10 64 位的 MongoDB 下载

c# - WebView2 下载进度

c# - 在哪里生成 SignInManager IdentityUser .cshtml 文件

c# - 如何在实现 Url 路由后修复路径(ASP.NET 4.0 webforms)

asp.net - 无法为 ASP.NET.Core 应用程序加载文件或程序集 microsoft.visualstudio.editor.razor 2017

asp.net - 展示我的开发技能的最佳网站是什么?