MVC.在新窗口中打开文件,而不是下载
本文关键字:下载 在新窗口中打开 文件 MVC | 更新日期: 2023-09-27 18:14:27
我的要求是在单击下载链接后在新窗口/选项卡中打开文件。尽管将内容设置为"inline",但该文件始终被下载。
如何在新的选项卡或窗口中打开PDF文件,而不是下载它(使用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");
}
建议使文件在新的选项卡/窗口中自动打开,而不是仅仅下载将有很大的帮助!谢谢!
找到答案了。
要在新窗口中打开文件,必须做两件事-
1。内容处置必须设置为inline
2。内容类型应设置为正在下载的文件对应的类型-
application/pdf -用于pdf文件
application/xml -用于xml文件
盾应用程序/。Ms-excel -用于XLS文件等
试试下面的代码。
@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");
}