若要實作ASP MVC下載檔案的功能
需要先達成以下兩件事:
1.指定Content-Type (告訴用戶端瀏覽器欲回應的內容)
string file = @"C:\Users\Administrator\Downloads\SQLEXPRADV_x64_ENU.exe";
string contentType = MimeMapping.GetMimeMapping(file);
|
2. 指定Content-Disposition(告訴用戶端瀏覽器如何處理附加文件)
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "SQLEXPRADV_x64_ENU.exe ",
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
|
其中 Inline 設為 false 表示不要在瀏覽器上打開
最後, 回傳 FileStreamResult
return File(
new FileStream(file, FileMode.Open, FileAccess.Read)
, contentType);
|
完整的程式碼如下:
public ActionResult Download()
{
FileInfo fl = new FileInfo(@"C:\Users\Administrator\Downloads\SQLEXPRADV_x64_ENU.exe");
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fl.Name,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var readStream = new FileStream(fl.FullName, FileMode.Open, FileAccess.Read);
string contentType = MimeMapping.GetMimeMapping(fl.FullName);
return File(readStream, contentType);
}
|
若下載的檔案太大, 需要將Response.BufferOutput 設為false
不然由於IIS的限制,可能會讓我們遇到 Overflow or underflow in the arithmetic operation的錯訊息
public ActionResult LargeDownload()
{
FileInfo fl = new FileInfo(@"C:\Users\Administrator\Downloads\SQLEXPRADV_x64_ENU.exe");
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fl.Name,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
Response.BufferOutput = false;
var readStream = new FileStream(fl.FullName, FileMode.Open, FileAccess.Read);
string contentType = MimeMapping.GetMimeMapping(fl.FullName);
return File(readStream, contentType);
}
|
補充:
Content-disposition:
指定用戶端瀏覽器如何處理附加文件
In a regular HTTP response, the
Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally. |
常用的設定有
Content-Disposition: inline
Content-Disposition: attachment
Content-Disposition: attachment; filename="filename.jpg"
|
(Default 設定為inline, 就是直接在瀏覽器上打開)
留言
張貼留言