ASP.NET 輸出 Word 文件本質上是:設定正確的 MIME 類型 → 讀取檔案二進位流 → 寫入 HTTP 回應流。關鍵在於 Content-Type 設為 application/msword,並可選擇性加上 Content-Disposition 標頭控制瀏覽器行為(直接開啟或另存新檔)。
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/msword";
string path = Server.MapPath("C#語言參考.doc");
Response.WriteFile(path);
Response.Flush();
Response.Close();
特點:一行 WriteFile 完成讀取與輸出,適合小檔案、簡單下載情境。但無法自訂下載檔名(瀏覽器會用原檔名或 URL 尾段)。
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/msword";
string path = Server.MapPath("C#語言參考.doc");
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
Response.WriteFile(path, 0, fs.Length); // 可控制 offset 與 length
fs.Close();
進階用途:WriteFile 多載支援 offset 與 length 參數,可實現斷點續傳或分段輸出大檔案,減少記憶體壓力。
string path = Server.MapPath("C#語言參考.doc");
FileInfo file = new FileInfo(path);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] fileData = new byte[file.Length];
fs.Read(fileData, 0, (int)file.Length);
fs.Close();
Response.Clear();
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename=自訂檔名.doc");
Response.BinaryWrite(fileData);
Response.End();
關鍵優勢:
Content-Disposition: attachment;filename=... 強制瀏覽器彈出「另存新檔」對話框,且可自訂下載檔名(解決中文檔名編碼問題)BinaryWrite 直接寫入位元組陣列,避免文字編碼轉換錯誤Response.End() 立即終止管線,確保無額外輸出干擾| 維度 | 方法一 WriteFile | 方法二 FileStream+WriteFile | 方法三 BinaryWrite |
|---|---|---|---|
| 程式碼複雜度 | 最低 | 中等 | 較高 |
| 自訂下載檔名 | ❌ | ❌ | ✅ |
| 大檔案支援 | ⚠️ 記憶體壓力大 | ✅ 可分段讀取 | ⚠️ 需完整載入記憶體 |
| 斷點續傳潛力 | ❌ | ✅ 配合 Range 標頭 | ❌ |
| 適用情境 | 小檔、簡單下載 | 大檔、需流控 | 需自訂檔名、中文檔名 |
Response.Clear();
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename=大檔.doc");
Response.BufferOutput = false; // 關閉緩衝,即時輸出
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) {
byte[] buffer = new byte[8192]; // 8KB 緩衝區
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) {
Response.OutputStream.Write(buffer, 0, bytesRead);
Response.Flush(); // 即時推送給客戶端
}
}
Response.End();
此模式不將整檔載入記憶體,適合 100MB+ 的大型 Word 文件輸出,配合 Response.BufferOutput = false 實現真正的串流傳輸。
filename=" + HttpUtility.UrlEncode("中文檔名.doc", Encoding.UTF8) + "(現代瀏覽器支援 RFC 5987 格式:filename*=UTF-8''...)Response.Clear() 清除前置輸出,避免 HTML/空白字元混入二進位流依據專案需求選擇適當方法,並注意記憶體管理與編碼細節,即能穩健實作 Word 文件下載功能。