在ASP.NETMVC中返回要查看/下載的文件我在將存儲(chǔ)在數(shù)據(jù)庫(kù)中的文件發(fā)送回ASP.NETMVC中的用戶時(shí)遇到了問題。我想要的是一個(gè)列出兩個(gè)鏈接的視圖,一個(gè)是查看文件并讓發(fā)送到瀏覽器的mimetype決定如何處理它,另一個(gè)是強(qiáng)制下載。如果我選擇查看一個(gè)名為SomeRandomFile.bak而且瀏覽器沒有一個(gè)相關(guān)的程序來打開這種類型的文件,那么我對(duì)它默認(rèn)的下載行為沒有問題。但是,如果我選擇查看一個(gè)名為SomeRandomFile.pdf或SomeRandomFile.jpg我想簡(jiǎn)單地打開文件。但是我也希望將下載鏈接保持在一邊,這樣無論文件類型如何,我都可以強(qiáng)制下載提示符。這有道理嗎?我試過了FileStreamResult它適用于大多數(shù)文件,默認(rèn)情況下,它的構(gòu)造函數(shù)不接受文件名,因此未知文件根據(jù)url(它不知道要根據(jù)內(nèi)容類型提供的擴(kuò)展名)分配文件名。如果我通過指定文件名來強(qiáng)制文件名,我就失去了瀏覽器直接打開文件的能力,并得到了下載提示。有沒有其他人遇到過這種情況。這些就是我迄今為止嘗試過的例子。//Gives me a download prompt.return File(document.Data, document.ContentType, document.Name);//Opens if it is a known extension type, downloads otherwise (download has bogus name and missing extension)return new FileStreamResult
(new MemoryStream(document.Data), document.ContentType);//Gives me a download prompt (lose the ability to open by default if known type)return new FileStreamResult(new MemoryStream(document.Data),
document.ContentType) {FileDownloadName = document.Name};有什么建議嗎?最新情況:這個(gè)問題似乎引起了很多人的共鳴,所以我想我應(yīng)該發(fā)布一個(gè)更新。Oskar添加的關(guān)于國(guó)際字符的公認(rèn)答案的警告是完全有效的,由于使用了ContentDisposition班級(jí),等級(jí)。從那以后,我更新了我的實(shí)現(xiàn)來修復(fù)這個(gè)問題。雖然下面的代碼是我最近在ASP.NETCore(完整框架)應(yīng)用程序中出現(xiàn)的這個(gè)問題的代碼,但它也應(yīng)該在舊的MVC應(yīng)用程序中進(jìn)行最小的更改,因?yàn)槲沂褂玫氖荢ystem.Net.Http.Headers.ContentDispositionHeaderValue班級(jí),等級(jí)。using System.Net.Http.Headers;public IActionResult Download(){
Document document = ... //Obtain document from database context
//"attachment" means always prompt the user to download
//"inline" means let the browser try and handle it
var cd = new ContentDispositionHeaderValue("attachment")
{
FileNameStar = document.FileName
};
Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
return File(document.Data, document.ContentType);}// an entity class for the document in my database public class Document{
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
//Other properties left out for brevity}
在ASP.NETMVC中返回要查看/下載的文件
阿波羅的戰(zhàn)車
2019-06-14 15:11:44