Controller 接收圖片 URL 參數,從遠程服務器讀取圖片流,設置響應頭實現瀏覽器「另存為」下載,支援中文檔名跨瀏覽器兼容。
@RequestMapping("/download")
public void downloadMedia(HttpServletResponse response, HttpServletRequest request) throws IOException {
request.setCharacterEncoding("UTF-8");
String fileName = request.getParameter("fileName");
// 解決 GET 參數中文亂碼
fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8").replace(" ", "%20");
// 設置響應頭:強制下載、檔名編碼兼容 IE / 非 IE
response.setContentType("application/octet-stream");
String agent = request.getHeader("User-Agent");
boolean isIE = agent != null && agent.contains("MSIE");
String encodedName = isIE ? URLEncoder.encode(fileName, "UTF-8")
: new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + encodedName);
// 流式傳輸,避免大文件 OOM
try (InputStream in = new URL(fileName).openStream();
OutputStream out = response.getOutputStream()) {
IOUtils.copy(in, out); // commons-io
out.flush();
}
}
URLEncoder,Chrome/Firefox 需 ISO-8859-1 包裝 UTF-8 位元組。IOUtils.copy 或手動 8KB 緩衝區,避免將大圖全量載入記憶體。replace(" ", "%20") 防止 MalformedURLException。<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>