【问题标题】:ASP.NET MVC - Download PDF file in same window not workingASP.NET MVC - 在同一窗口中下载 PDF 文件不起作用
【发布时间】:2021-09-06 08:22:03
【问题描述】:

我已经下载了从控制器方法生成的 PDF 文件(不打开)。文件正在新的单独窗口中打开。我在服务器端生成 MemoryStream。我要在同一个窗口返回给客户端,这里不用打开,在同一个客户端窗口下载即可。 下面的代码我试过了-

服务器-

public async Task<ActionResult> DownloadReport(string id, string reportType="")
{
  var fileData = await GetReport(id, reportType); 
  // here fileData is MemoryStream

  return  File(fileData, "application/pdf");
}

html代码-

 @Html.ActionLink("Download", "DownloadReport","Files", new { id = "abc" },null)

【问题讨论】:

  • 我的一部分认为您正在与浏览器设置作斗争。看起来有一些方法可以通过修改标题内容处置来诱使浏览器进入文件保存对话框。有关一些想法,请参阅此线程:stackoverflow.com/questions/12035410/save-download-file-dialog
  • @kd345205 我不想使用文件对话框。只需在同一窗口中从服务器下载文件,无需打开。

标签: javascript c# asp.net-mvc memorystream


【解决方案1】:

使用Content-Disposition 标头

   public async Task<ActionResult> DownloadReport(string id, string reportType="")
    {
      var fileData = await GetReport(id, reportType); 
      // here fileData is MemoryStream
      Response.AddHeader("Content-Disposition", "attachment;filename=file.pdf");
      return  File(fileData, "application/pdf");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2015-08-07
    • 1970-01-01
    • 2019-07-26
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多