在浏览器中打开文件而不是下载它 [英] Make a file open in browser instead of downloading it
问题描述
我有一个 MVC 项目,它将向用户显示一些文档.文件当前存储在 Azure blob 存储中.
I have an MVC project that will display some documents to users. The files are currently stored in Azure blob storage.
目前,文档是从以下控制器操作中检索的:
Currently, the documents are retrieved from the following controller action:
[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);
}
现在,当用户点击如下链接时:
Right now, when a user clicks on a link like the following:
<a target="_blank" href="http://...controller//GetDocument?zipCode=84016&loanNumber=12345678classification=document&fileName=importantfile.pdf
然后,文件会下载到浏览器的下载文件夹中.我想要发生的(我认为是默认行为)是让文件简单地显示在浏览器中.
Then, the file downloads to their browser's downloads folder. What I would like to happen (and I thought was default behavior) is for the file to simply be displayed in the browser.
我尝试更改 mimetype 并将返回类型更改为 FileResult 而不是 ActionResult,但均无济于事.
I have tried changing the mimetype and changing the return type to FileResult instead of ActionResult, both to no avail.
如何让文件在浏览器中显示而不是下载?
How can I make the file display in the browser instead of downloading?
推荐答案
感谢所有的答案,解决方案是所有这些的组合.
Thanks to all the answers, the solution was a combination of all of them.
首先,因为我使用的是 byte[]
,控制器动作需要是 FileContentResult
而不仅仅是 FileResult
.发现这要归功于:有什么区别在 ASP.NET MVC 中的四个文件结果之间
First, because I was using a byte[]
the controller action needed to be FileContentResult
not just FileResult
. Found this thanks to: What's the difference between the four File Results in ASP.NET MVC
其次,mime 类型不能是 octet-stream
.据说,使用流会导致浏览器只下载文件.我不得不更改 application/pdf
类型.不过,我需要探索一个更强大的解决方案来处理其他文件/mime 类型.
Second, the mime type needed to NOT be a octet-stream
. Supposedly, using the stream causes the browser to just download the file. I had to change the type application/pdf
. I will need to explore a more robust solution to handle other file/mime types though.
第三,我必须添加一个将 content-disposition
更改为 inline
的标题.使用这篇文章我发现我必须修改我的代码防止重复标题,因为内容处置已经被设置为 attachment
.
Third, I had to add a header that changed the content-disposition
to inline
. Using this post I figured out I had to modify my code to prevent duplicate headers, since the content-disposition was already being set to 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);
}
这篇关于在浏览器中打开文件而不是下载它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!