問題根源:瀏覽器 URL 長度限制
| 瀏覽器 | URL 最大長度 | 備註 |
| IE (全版本) | 2,083 字元 | 最嚴格,超過無反應 |
| Chrome | 8,182 字元 | 文檔建議 < 2MB |
| Firefox | 65,536 字元 | 實測支援更長 |
| Safari | 80,000 字元 | |
| Edge (Chromium) | 8,182 字元 | 同 Chrome |
伺服器端也有限制(IIS 預設 16KB、Nginx `large_client_header_buffers`、Apache `LimitRequestLine`)。
失效場景重現
// 問題代碼:大量資料拼接在 URL
var hugeData = "..."; // 超過 2KB 字串
var url = "export.action?data=" + encodeURIComponent(hugeData);
window.location.href = url; // IE 直接失效,無錯誤提示
解決方案:POST 提交 + Session 中轉
流程圖解
前端 後端
│ │
│── POST /saveData {data} ───▶│ 儲存 data 到 Session
│ │ 回傳 {success: true}
│◀──── {success: true} ───────│
│ │
│── GET /export (無參數) ─────▶│ 從 Session 讀取 data
│ │ 生成 Excel 回傳檔案
│◀──── Excel 檔案流 ──────────│
│ │
前端實作
function exportLargeData(data) {
var saveUrl = '<%=basePath%>saveExportData.action';
var exportUrl = '<%=basePath%>exportData.action';
// 步驟 1:POST 送大資料存 Session
$.post(saveUrl, { exportData: data }, function(result) {
if (result.success) {
// 步驟 2:GET 請求導出(URL 乾淨無參數)
window.location.href = exportUrl + '?t=' + Date.now(); // 防快取
} else {
alert('資料準備失敗:' + result.message);
}
}, 'json').fail(function() {
alert('網路錯誤,請重試');
});
}
後端實作
// Action 1:儲存大資料到 Session
public String saveExportData() {
String data = request.getParameter("exportData");
if (data != null && !data.isEmpty()) {
session.setAttribute("EXPORT_DATA_KEY", data);
writeJson("{success:true}");
} else {
writeJson("{success:false, message:'無資料'}");
}
return NONE;
}
// Action 2:從 Session 讀取並導出
public String exportData() {
String data = (String) session.getAttribute("EXPORT_DATA_KEY");
if (data == null) {
response.sendError(400, "無導出資料");
return NONE;
}
// 清除 Session 避免重複導出佔用記憶體
session.removeAttribute("EXPORT_DATA_KEY");
// 解析 data、生成 Excel、設定 Header 回傳
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=export.xls");
// ... Excel 生成邏輯 ...
return NONE;
}
替代方案對比
| 方案 | 優點 | 缺點 | 適用場景 |
| POST + Session(本文) | 相容所有瀏覽器、實現簡單 | 佔用 Session 記憶體、需兩次請求 |
傳統專案、中小資料量 |
| Form POST 直接下載 | 單次請求、無 Session 依賴 | 需動態建 form、回傳檔案流處理較複雜 |
現代專案、大檔案 |
| Blob + Object URL | 純前端生成、無後端參與 | 受限於瀏覽器記憶體、大檔案易崩潰 |
純前端報表、小資料 |
| 分塊上傳 + 合併 | 突破所有大小限制 | 實現複雜、需後端配合 |
超大檔案(>100MB) |
Form POST 直接下載實作(推薦現代專案)
function exportByFormPost(data) {
var form = document.createElement('form');
form.method = 'POST';
form.action = '<%=basePath%>exportDataDirect.action';
form.target = '_blank'; // 新分頁避免頁面跳轉
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'exportData';
input.value = data;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}