简体   繁体   English

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

[英]MVC.Net Open a file in a new window instead of downloading

My requirement is to open a file in a new window/tab upon clicking the download link. 我的要求是,单击下载链接后,在新窗口/选项卡中打开文件。 The file is always downloaded despite setting the content disposition to 'inline' as suggested in the below post. 尽管将内容分配设置为“内联”,但始终会下载该文件,如以下文章中所建议。

How to open PDF file in a new tab or window instead of downloading it (using asp.net)? 如何在新的标签页或窗口中打开PDF文件而不是下载文件(使用asp.net)?

My HTTP response is 我的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

My Controller Action is as below - 我的控制器动作如下-

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

Suggestions to make the file open automatically in a new tab/window instead of just being downloaded would be of great help! 建议在新标签页/窗口中自动打开文件而不是仅下载文件,这将对您大有帮助! Thanks! 谢谢!

Found the answer. 找到了答案。

2 things have to be done for the file to open in a new window - 要在新窗口中打开文件,必须完成2件事-

1.content-disposition must be set to inline 1.content-disposition必须设置为inline

2.the content type should be set to the type corresponding to the file being downloaded - 2.内容类型应设置为与正在下载的文件相对应的类型-

application/pdf - for pdf files 应用程序/ pdf-pdf文件

application/xml - for xml files application / xml-用于xml文件

application/vnd.ms-excel - for xls files and so on. application / vnd.ms-excel-用于xls文件等。

Try the following code. 请尝试以下代码。

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

Since we are returning to the view mode, there is no need to mention about header response 由于我们将返回查看模式,因此无需提及标头响应

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM