MVC.Net在新窗口中打开文件而不是下载

时间:2016-10-24 03:34:37

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

我的要求是在点击下载链接后在新窗口/标签中打开文件。尽管将内容处置设置为' inline',但始终会下载该文件。如下文所述。

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");
    }

在新的标签/窗口中自动打开文件而不是仅仅下载的建议会有很大的帮助!谢谢!

2 个答案:

答案 0 :(得分:2)

找到答案。

要在新窗口中打开文件,必须完成两件事 -

1.content-disposition必须设置为inline

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

application / pdf - for pdf files

application / xml - 用于xml文件

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

答案 1 :(得分:1)

请尝试以下代码。

@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");
    }
相关问题