下載功能是 Web 開發的常客。它的運作原理其實很簡單:伺服器在響應頭中聲明「這是附件」,瀏覽器就會跳出另存新檔視窗,而不是試圖在頁面中開啟它。
@RequestMapping(value = "download.html", method = RequestMethod.GET)
public void download(String resourceid, HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("charset=UTF-8");
File file = new File(path);
response.setHeader("Content-Disposition", "attachment; filename=a");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
try {
fis = new FileInputStream(file.getAbsolutePath());
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
int bytesRead = 0;
byte[] buffer = new byte[5 * 1024];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
} catch (E e) {
} finally {
try {
bis.close(); bos.close(); fos.close(); fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
流程是:找出檔案 → 設定響應頭 → 以串流形式把位元組寫到瀏覽器。瀏覽器在標頭中看到主體是串流檔案,便自動呼叫另存新檔視窗。
關鍵在 Content-Disposition。它是 MIME 協議的擴充,用於指示客戶端該如何顯示回應內容,有兩個主要取值:
· inline —— 嘗試在瀏覽器內線上開啟
· attachment —— 作為附件下載
這裡設為 attachment,因此會觸發下載行為。
1. 表單提交
<form action='download.html' method='post'> <input type='submit'/> </form>
2. 隱藏 iframe
var iframe = "<iframe style='display:none' src='download.html'></iframe>"; document.body.append(iframe);
iframe 被掛到 body 上時會自動請求該連結。因為 Content-Disposition 是 attachment,瀏覽器不會把串流當頁面渲染,而是觸發下載,同時原頁面保持不動——這是不跳頁的關鍵優勢。
3. window.open
window.open("download.html");
最簡單,但會被瀏覽器的彈出視窗阻擋器攔截(除非在直接的使用者手勢觸發鏈中呼叫)。
用 try-with-resources 取代手動關閉。範例中 finally 裡連續 close 四個串流,若前面的 close 拋錯,後面的就不會執行,造成資源洩漏:
try (InputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
byte[] buffer = new byte[8192];
int len;
while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); }
}
filename 要編碼。直接寫中文檔名會亂碼,且需防 header injection:
String fileName = URLEncoder.encode("報表.xlsx", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-Disposition",
"attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + fileName);
不要 catch 之後什麼都不做。範例中的空 catch 區塊會讓錯誤完全消失,出問題時無從追查,至少該 log.error。
用程式化方式設定 Content-Disposition。Spring 較新版本建議用 ContentDisposition.attachment().filename(...).build() 產生標頭值,會自動處理編碼與轉義。
若走 XHR 下載,需注意 responseType 設為 'blob',且無法直接讀取 Content-Disposition 中的中文檔名(部分瀏覽器限制),實務上多由前端自行指定檔名。