萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Java 後端與 JavaScript 前端實現文件下載完整方案

整體流程

前端請求 → 後端查找文件 → 設置響應頭 → 輸出文件流 → 瀏覽器彈出「另存為」

後端:Spring MVC 實現

@GetMapping("/download")
public void download(@RequestParam String resourceId, HttpServletResponse response) throws IOException {
    // 1. 定位文件 (示例路徑,實際應從資料庫/配置獲取)
    File file = new File("/data/uploads/" + resourceId);
    if (!file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // 2. 關鍵響應頭
    response.setContentType("application/octet-stream"); // 二進制流
    // Content-Disposition: attachment 強制下載;filename* 支援 UTF-8 編碼中文文件名 (RFC 5987)
    String fileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"; filename*=UTF-8''" + fileName);
    response.setContentLengthLong(file.length()); // 支援大文件

    // 3. 流式輸出 (使用 try-with-resources 自動關閉)
    try (FileInputStream fis = new FileInputStream(file);
         BufferedInputStream bis = new BufferedInputStream(fis);
         OutputStream os = response.getOutputStream()) {

        byte[] buffer = new byte[8192]; // 8KB 緩衝區
        int bytesRead;
        while ((bytesRead = bis.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
    }
}

關鍵點解析

響應頭作用注意事項
Content-Type告知瀏覽器內容類型application/octet-stream 通用二進制;若知具體類型可設 application/pdf 等
Content-Disposition控制顯示方式attachment 強制下載;inline 瀏覽器內打開 (PDF/圖片);文件名需雙重編碼兼容新舊瀏覽器
Content-Length文件大小啟用下載進度條、支援斷點續傳基礎
Cache-Control緩存控制私有文件建議 no-store, must-revalidate

前端三種觸發下載方式

1. 普通 <form> 提交 (最簡單、支援 POST 參數)

<form action="/download" method="post">
  <input type="hidden" name="resourceId" value="abc123">
  <button type="submit">下載附件</button>
</form>

2. 隱藏 <iframe> (無刷新、保留頁面狀態)

function downloadByIframe(url) {
  var iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  iframe.src = url;
  document.body.appendChild(iframe);
  // 可選:延遲移除
  setTimeout(() => document.body.removeChild(iframe), 10000);
}
// 使用
downloadByIframe('/download?resourceId=abc123');

3. window.open (新標籤/彈窗,易被攔截)

window.open('/download?resourceId=abc123', '_blank');

4. 現代最佳:AJAX + Blob + Object URL (支援進度、大文件、認證頭)

async function downloadFile(url, filename) {
  const response = await fetch(url, {
    method: 'GET',
    credentials: 'include', // 攜帶 Cookie
    headers: { 'Authorization': 'Bearer ' + getToken() } // 攜帶 Token
  });

  if (!response.ok) throw new Error('下載失敗: ' + response.status);

  const blob = await response.blob();
  const blobUrl = URL.createObjectURL(blob);

  const a = document.createElement('a');
  a.href = blobUrl;
  a.download = filename || 'download';
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(blobUrl); // 釋放記憶體
}

大文件斷點續傳提示

  • 後端需支援 Range / Content-Range 請求頭 (HTTP 206 Partial Content)。
  • 前端使用 axios 或 fetch 設置 Range: bytes=0- 分片下載,合併 Blob。
  • 或採用成熟庫:resumable.js、uppy。

總結

  • 後端核心:正確設置 Content-Disposition: attachment、流式輸出、文件名 UTF-8 編碼。
  • 前端選擇:表單/iframe 簡單場景;AJAX+Blob 複雜場景 (認證、進度、大文件)。
  • 安全:驗證權限、防止路徑遍歷、限制下載頻率、記錄審計日誌。
copyright © 萬盛學電腦網 all rights reserved