public abstract class FileResult : ActionResult
{
protected FileResult(string contentType);
public override void ExecuteResult(ControllerContext context);
protected abstract void WriteFile(HttpResponseBase response);
public string ContentType { get; }
public string FileDownloadName { get; set; } // 設定則啟用附件模式
}
Response.ContentType。FileDownloadName 非空,產生 Content-Disposition: attachment; filename=... 標頭 (透過 ContentDispositionUtil)。WriteFile(response) 寫入檔案內容。public class FileContentResult : FileResult
{
public byte[] FileContents { get; }
public FileContentResult(byte[] fileContents, string contentType);
protected override void WriteFile(HttpResponseBase response)
=> response.OutputStream.Write(FileContents, 0, FileContents.Length);
}
// Controller 方法
protected FileContentResult File(byte[] fileContents, string contentType);
protected virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);
適用:動態產生內容 (報表、圖表、加密檔案) 或小檔案讀入記憶體。
public class FilePathResult : FileResult
{
public string FileName { get; }
public FilePathResult(string fileName, string contentType);
protected override void WriteFile(HttpResponseBase response)
=> response.TransmitFile(FileName); // 高效傳輸,支援大檔案、斷點續傳
}
// Controller 方法
protected FilePathResult File(string fileName, string contentType);
protected virtual FilePathResult File(string fileName, string contentType, string fileDownloadName);
適用:伺服器現有靜態檔案 (PDF、影片、大型下載)。TransmitFile 直接由核心模式傳輸,不佔用 Managed 記憶體。
public class FileStreamResult : FileResult
{
public Stream FileStream { get; }
public FileStreamResult(Stream fileStream, string contentType);
protected override void WriteFile(HttpResponseBase response)
{
var buffer = new byte[4096];
int count;
while ((count = FileStream.Read(buffer, 0, buffer.Length)) > 0)
response.OutputStream.Write(buffer, 0, count);
}
}
// Controller 方法
protected FileStreamResult File(Stream fileStream, string contentType);
protected virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);
適用:動態串流來源 (資料庫 BLOB、雲端儲存、壓縮串流、加密串流)。需注意 FileStream.Position 及生命週期管理。
| 副檔名 | Content-Type |
|---|---|
| application/pdf | |
| .jpg/.jpeg | image/jpeg |
| .png | image/png |
| .zip | application/zip |
| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
FileDownloadName,瀏覽器彈出下載對話框。FileResult 三兄弟涵蓋所有檔案回應情境:FileContentResult (記憶體陣列)、FilePathResult (實體檔案、高效)、FileStreamResult (串流來源)。選擇原則:靜態大檔用 FilePathResult,動態串流用 FileStreamResult,小型動態內容用 FileContentResult。