幾乎每個 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;
try {
bis = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[5 * 1024];
int bytesRead = 0;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 依序關閉串流,避免檔案描述符洩漏
}
}
Spring MVC 把請求導到這個方法後,程式先找出目標檔案、設定回應標頭,再把內容以串流形式寫回瀏覽器。瀏覽器一看主體是檔案流,就會跳出「另存新檔」的視窗。
真正決定「下載」還是「開啟」的,是 Content-Disposition 這個回應標頭。它是 MIME 協定的擴充,用來告訴用戶端該如何處理附件,有兩個常見值:
inline // 直接在瀏覽器內開啟 attachment // 當成附件下載
我們設成 attachment,瀏覽器便會觸發下載行為。
<form action='download.html' method='post'> <input type='submit'/> </form>
var iframe = "<iframe style='display:none' src='download.html'></iframe>"; document.body.appendChild(iframe);
iframe 一被掛進 body,瀏覽器就會自動對該 src 發出請求,頁面本身完全不跳轉,適合「下載但不離開當前頁」的情境。
window.open("download.html");
最直白的一種,但可能被瀏覽器的彈出視窗阻擋器攔下來。
實務上還有兩個細節值得注意:檔名若含中文,建議用 URL编码 或 RFC 5987 的 filename*=UTF-8'' 寫法,避免在不同瀏覽器上變成亂碼;另外記得對 resourceid 之類的傳入參數做權限與路徑驗證,否則容易留下任意檔案讀取的漏洞。