首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 檔案下載中文檔名亂碼解決:UrlEncode 編碼與 URL 路徑附加檔名兩種方案比較

     編輯:關於ASP.NET

使用 Response.AppendHeader("Content-Disposition", "attachment; filename=...") 時,中文檔名在不同瀏覽器/編碼下易產生亂碼。本文提供兩種徹底解決方案。

問題重現

Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"報表.pdf\"");
Response.BinaryWrite(fileBytes);
Response.End();
// 結果:IE 可能顯示「報表.pdf」,Chrome/Firefox 顯示亂碼或截斷

方案一:Server.UrlEncode 編碼 (傳統相容)

string fileName = "報表.pdf";
string encodedName = Server.UrlEncode(fileName); // %E5%A0%B1%E8%A1%A8.pdf
Response.AppendHeader("Content-Disposition", $"attachment; filename=\"{encodedName}\"");
// 瀏覽器下載時自動解碼為「報表.pdf」
  • 優點:相容舊版瀏覽器 (IE6+)、實作簡單。
  • 缺點:
    1. 空格編碼為 + 而非 %20,部分瀏覽器解碼異常。
    2. 2. RFC 5987 標準建議使用 filename*=UTF-8''encoded 格式。

方案二:URL 路徑附加檔名 (極簡、現代瀏覽器完美)

原理:瀏覽器從請求 URL 最後一段路徑推斷預設檔名。

// 原下載頁面:Download.aspx?id=123
// 改為:Download.aspx/報表.pdf?id=123

// 路由設定 (ASP.NET 4.0+ Routing / MVC / Core 內建支援)
// WebForms 需在 Global.asax 註冊路由
routes.MapPageRoute("Download", "Download/{fileName}", "~/Download.aspx");
// Download.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
    string id = Request.QueryString["id"]; // 或 RouteData.Values["id"]
    string fileName = GetFileNameFromDb(id); // "報表.pdf"
    byte[] bytes = GetFileBytes(id);

    Response.Clear();
    Response.ContentType = "application/pdf";
    // 不需 AppendHeader filename,瀏覽器自動取 URL 最後段 "報表.pdf"
    Response.BinaryWrite(bytes);
    Response.End();
}
  • 優點:
    1. 完全避開 Header 編碼地雷區。
    2. 2. URL 可見、可分享、可書籤、SEO 友善。 3. 符合 RFC 6266 建議 (瀏覽器優先使用 URL 路徑)。
  • 注意:
    1. 檔名中不可含 / \ : * ? " < > | 等非法路徑字元,需預先替換或移除。
    2. 2. 路由須配合 runAllManagedModulesForAllRequests="true" (IIS 7+) 或 Wildcard Mapping (IIS 6)。

企業級最佳實踐:雙重保障

string safeName = Regex.Replace(fileName, @"[\\/:*?""<>|]", "_"); // 淨化
string encoded = Server.UrlEncode(safeName);
Response.AppendHeader("Content-Disposition", $"attachment; filename=\"{encoded}\"; filename*=UTF-8''{encoded}");
// 同時支援舊式 filename 與 RFC 5987 filename*

結合路由友善 URL + 雙重 Header,達成跨瀏覽器、跨版本、符合標準的完美下載體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved