首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

AJAX 返回中文文件名出現亂碼:後端編碼設置與前端解碼解決方案

     編輯:程式設計綜合問答

問題現象

  • 後端生成 Excel,文件名含中文 (如 `報表_2023.xlsx`)。
  • 後端日誌輸出文件名正常顯示中文。
  • AJAX `success` 回調接收到的字符串**中文變問號/亂碼**。
  • 前端頁面已設置 ``。

根本原因

**響應內容編碼與聲明不一致**。

  • 後端默認響應 `Content-Type: text/plain;charset=ISO-8859-1` (或無 charset)。
  • 瀏覽器按 ISO-8859-1 解碼 UTF-8 位元組 → 亂碼。
  • 前端頁面 charset 僅影響頁面自身解析,**不影響 AJAX 響應解碼** (響應由 `Content-Type` header 決定)。

解決方案

方案一:後端設置響應編碼為 UTF-8 (推薦、徹底)

Java (Servlet/Controller/Handler):


response.setContentType("text/plain;charset=UTF-8"); // 或 application/json
response.setCharacterEncoding("UTF-8");
// 寫入內容
response.getWriter().write(filePath);

Spring MVC @ResponseBody:


@GetMapping(value = "/export", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String export() { ... }

PHP:


header('Content-Type: text/plain; charset=UTF-8');
echo $filePath;

方案二:前端強制指定 xhr.responseType / overrideMimeType


$.ajax({
    url: '/export',
    // 強制覆蓋 MIME 類型及編碼
    beforeSend: function(xhr) {
        xhr.overrideMimeType('text/plain;charset=UTF-8');
    },
    success: function(filePath) {
        $(".download").attr("href", filePath);
    }
});

或使用 `xhrFields: { responseType: 'text' }` 配合服務端正確 header。

方案三:文件名 URL 編碼傳輸 (最穩健)

後端返回 **URL 編碼後的文件名**,前端解碼:


// 後端 Java
String encodedName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
response.getWriter().write(encodedName);

// 前端 JS
success: function(encodedPath) {
    var decodedPath = decodeURIComponent(encodedPath);
    $(".download").attr("href", decodedPath);
}

優點:純 ASCII 傳輸,完全規避編碼問題;缺點:需雙端配合編解碼。

最佳實踐建議

  1. 統一 UTF-8:項目全鏈路 (DB、Java/Php 源文件、HTML、JS、CSS、HTTP Header、JS 文件編碼) 強制 UTF-8。
  2. RESTful API 返回 JSON:`{ "path": "..." }`,設置 `produces = "application/json;charset=UTF-8"`,前端 `dataType: 'json'` 自動處理編碼。
  3. 文件下載專用端點:AJAX 僅獲取下載 URL,實際下載用 `` 或 `location.href`,由瀏覽器處理 `Content-Disposition` 編碼 (RFC 5987)。

驗證步驟

  1. 瀏覽器 F12 Network 面板 → 查看 AJAX 響應 Headers → 確認 `Content-Type: text/plain;charset=UTF-8`。
  2. Response 內容 → 確認中文正常顯示。
  3. JS 變量 → `console.log(filePath)` 確認解碼正確。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved