在浏览器中打开文件而不是下载它

Tre*_*vor 48 c# asp.net-mvc azure

我有一个MVC项目,将向用户显示一些文档.这些文件当前存储在Azure blob存储中.

目前,从以下控制器操作中检索文档:

[GET("{zipCode}/{loanNumber}/{classification}/{fileName}")]
public ActionResult GetDocument(string zipCode, string loanNumber, string classification, string fileName)
{
    // get byte array from blob storage
    byte[] doc = _docService.GetDocument(zipCode, loanNumber, classification, fileName);
    string mimeType = "application/octet-stream";
    return File(doc, mimeType, fileName);
}
Run Code Online (Sandbox Code Playgroud)

现在,当用户点击如下链接时:

<a target="_blank" href="http://...controller//GetDocument?zipCode=84016&loanNumber=12345678classification=document&fileName=importantfile.pdf
Run Code Online (Sandbox Code Playgroud)

然后,该文件将下载到其浏览器的下载文件夹中.我想要发生的事情(我认为是默认行为)是文件只是在浏览器中显示.

我已经尝试更改mimetype并将返回类型更改为FileResult而不是ActionResult,两者都无济于事.

如何在浏览器中显示文件而不是下载?

Tre*_*vor 88

感谢所有答案,解决方案是所有这些解决方案的组合.

首先,因为我使用byte[]的控制器操作FileContentResult不仅仅是FileResult.发现这要归功于:ASP.NET MVC中的四个文件结果之间有什么区别

其次,mime类型不需要是a octet-stream.据说,使用流导致浏览器只下载文件.我不得不改变类型application/pdf.我需要探索更强大的解决方案来处理其他文件/ mime类型.

第三,我不得不补充说,改变了一个标题content-dispositioninline.使用这篇文章,我发现我必须修改我的代码以防止重复的标题,因为内容处置已被设置为attachment.

成功的代码:

public FileContentResult GetDocument(string zipCode, string loanNumber, string classification, string fileName)
{
    byte[] doc = _docService.GetDocument(zipCode, loanNumber, classification, fileName);
    string mimeType = "application/pdf"
    Response.AppendHeader("Content-Disposition", "inline; filename=" + fileName);
    return File(doc, mimeType);
} 
Run Code Online (Sandbox Code Playgroud)

  • 获取mimetype的更强大的解决方案:`return File(doc,MimeMapping.GetMimeMapping(fileName));` (18认同)

wel*_*gan 15

看起来有人刚才问了一个类似的问题:

如何强制pdf文件在浏览器中打开

回答说你应该使用标题:

Content-Disposition: inline; filename.pdf
Run Code Online (Sandbox Code Playgroud)