2013-10-16 210 views
37

我有一个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); 
} 

,当用户点击类似下面的链接:

目前,该文件是从以下控制器动作检索

<a target="_blank" href="http://...controller//GetDocument?zipCode=84016&loanNumber=12345678classification=document&fileName=importantfile.pdf 

然后,将文件下载到他们浏览器的下载文件夹。我想要发生的事情(我认为是默认行为)是让文件简单地显示在浏览器中。

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

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

+3

相当肯定的浏览器决定如何处理基础上,mime类型的文件。 http://www.webmaster-toolkit.com/mime-types.shtml – Tommy

+0

这就是我所怀疑的,所以我尝试了与.pdf相关的各种mimetypes并尝试打开文件,但每次都下载。当我在浏览器窗口中打开的其他网站上查看其他pdf时。 – Trevor

+2

内容处理标题的价值是什么? –

回答

76

感谢所有答案,解决方案是一个组合他们都是。

首先,因为我使用的是byte[],所以控制器操作需要为FileContentResult而不仅仅是FileResult。发现这个要归功于:What's the difference between the four File Results in ASP.NET MVC

其次,MIME类型不需要是octet-stream。据推测,使用该流会导致浏览器下载文件。我不得不改变类型application/pdf。我将需要探索更强大的解决方案来处理其他文件/ MIME类型。

第三,我不得不添加一个标题,将content-disposition更改为inline。使用this post我发现我不得不修改我的代码以防止重复标题,因为内容处置已被设置为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); 
} 
+14

更强大的解决方案获得mimetype:'返回文件(doc,MimeMapping.GetMimeMapping(fileName));' – Trevor

+1

真棒你解决了。我在上面的注释中提供的链接将允许您根据MimeTypes的文件扩展名创建一个字典。然后,只需创建一个静态函数,该文件接受一个文件扩展名,并为您期望的任何文件(我可能不会覆盖.crt)返回一个MIME类型。如果没有找到扩展名,则返回标准* application/octet-stream * – Tommy

+1

像魅力一样工作!最佳解决方案 – Khateeb321

3

浏览器应根据MIME类型决定下载或显示。

试试这个:

string mimeType = "application/pdf"; 
12

它看起来像别人问过类似的问题,前一阵子:

how to force pdf files to open in a browser

一个答案说你应该使用标题:

Content-Disposition: inline; filename.pdf 
+0

好的,所以不幸我尝试了这个,不得不按照链接帖子中的步骤操作,但它仍然不起作用。我尝试将返回类型更改为FileContentResult,但这也没有帮助。 – Trevor

+1

这绝对是解决方案的一部分,谢谢! – Trevor

+1

np,很高兴它解决了 – welegan

相关问题