透過設定 HTTP 回應標頭 Content-Disposition: attachment,強制瀏覽器彈出「另存新檔」對話框,而非直接開啟檔案。
protected String renderFile(String text, String fileName) throws IOException {
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("GB2312");
response.getWriter().write(text);
response.flushBuffer();
response.getWriter().close();
return null;
}
public String down() {
String dir = getFullPath() + "/upload/file/";
try {
if (!FileUtils.exists(dir)) new File(dir).mkdirs();
Random r = new Random(System.currentTimeMillis());
Integer randomInt = r.nextInt();
this.renderFile("test content:" + randomInt, randomInt + ".txt");
} catch (IOException e) {
e.printStackTrace();
this.renderText(e.getMessage());
}
return null;
}
<a href="down.action">下載</a>
Content-Disposition: attachment:指示瀏覽器下載而非顯示。application/octet-stream:通用二進位流 MIME 類型,適用任意檔案。filename 參數:建議經 URLEncoder.encode 處理中文檔名,避免亂碼。flushBuffer() 並 close() 確保資料完整送達。