Servlet 使用 `response.getOutputStream()` 輸出檔案,設定 `Content-Disposition: attachment`,但瀏覽器不彈出「另存新檔」對話框,無任何反應。
前端使用 **AJAX (XMLHttpRequest / fetch / jQuery.ajax)** 發起下載請求。AJAX 請求的回應**僅在 JavaScript 可用**,瀏覽器**不會**自動處理 `Content-Disposition: attachment` 彈出下載對話框。
// 前端
window.location.href = '/downloadServlet?fileId=123'; // 或
// 下載
// 1. AJAX 請求驗證,成功後回傳下載 Token 或簽名 URL
// 2. 前端拿到 Token 後
window.location.href = '/downloadServlet?token=' + token; // 觸發瀏覽器下載
// 或使用 Blob + Object URL(現代瀏覽器)
fetch('/downloadServlet?fileId=123', {credentials: 'include'})
.then(res => res.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'filename.zip'; // 從 response headers 解析或指定
a.click();
URL.revokeObjectURL(url);
});
response.setContentType("application/octet-stream"); // 通用二進位
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
response.setContentLengthLong(file.length()); // 支援大檔案
// 輸出流寫入...
檔案下載**必須**由瀏覽器主導導航請求(``、`window.location`、`form submit`)觸發,AJAX 無法直接啟動瀏覽器下載 UI。