首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 從遠程服務器下載圖片並輸出至瀏覽器完整實作

     編輯:Java 相關知識

核心需求

Controller 接收圖片 URL 參數,從遠程服務器讀取圖片流,設置響應頭實現瀏覽器「另存為」下載,支援中文檔名跨瀏覽器兼容。

Spring MVC Controller 完整代碼

@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();
    }
}

關鍵技術點

  • 檔名編碼:IE 需 URLEncoder,Chrome/Firefox 需 ISO-8859-1 包裝 UTF-8 位元組。
  • 流式複製:使用 IOUtils.copy 或手動 8KB 緩衝區,避免將大圖全量載入記憶體。
  • 異常與資源關閉:採用 try-with-resources 確保流關閉。
  • URL 空格處理:replace(" ", "%20") 防止 MalformedURLException。

依賴坐標

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved