【问题标题】:MVC.Net Open a file in a new window instead of downloadingMVC.Net 在新窗口中打开文件而不是下载
【发布时间】:2017-03-05 18:04:51
【问题描述】:

我的要求是单击下载链接后在新窗口/标签中打开文件。尽管按照以下帖子中的建议将内容处置设置为“内联”,但始终会下载该文件。

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

我的 HTTP 响应是

HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0
Content-Type: application/octet-stream
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 5.2
content-disposition: inline;filename=FileName.pdf
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 141954

我的控制器动作如下 -

public async Task<FileContentResult> Index(string fileName)
    {
        byte[] document = await getFileContent("SomePathForTheFile");
        HttpContext.Response.AddHeader("content-disposition", "inline;filename=" + document.FileName);
        return File(document, "application/octet-stream");
    }

让文件在新选项卡/窗口中自动打开而不是仅仅被下载的建议会很有帮助!谢谢!

【问题讨论】:

  • 将您的 Content-Type 设置为 application/pdf
  • 谢谢!这对我有用。

标签: c# asp.net-mvc-4 download


【解决方案1】:

找到了答案。

要在新窗口中打开文件,必须做 2 件事 -

1.content-disposition 必须设置为内联

2.内容类型应设置为正在下载的文件对应的类型-

application/pdf - 用于 pdf 文件

application/xml - 用于 xml 文件

application/vnd.ms-excel - 用于 xls 文件等。

【讨论】:

    【解决方案2】:

    试试下面的代码。

    @Html.ActionLink("Home","Index",null,new { @target="_blank" })
    

    既然回到了视图模式,就不用提头部响应了

    public async Task<FileContentResult> Index(string fileName)
        {
            byte[] document = await getFileContent("SomePathForTheFile");
            return File(document, "application/octet-stream");
        }
    

    【讨论】:

    • 嗨,只有在将内容类型设置为“application/pdf”而不是“application/octet-stream”时,我才能正常工作。感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 2012-09-01
    • 2014-12-28
    • 2020-12-10
    • 2013-11-03
    • 2018-06-02
    • 1970-01-01
    • 2012-08-09
    • 2012-01-07
    相关资源
    最近更新 更多