JSP/Servlet 實現檔案下載核心在於設定正確的 HTTP 回應標頭,並以高效串流方式輸出檔案內容,避免大檔案載入記憶體導致 OOM。本文提供生產級下載工具類,支援斷點續傳、中文檔名編碼、大檔案分塊傳輸。
| 標頭 | 值範例 | 作用 |
|---|---|---|
| Content-Disposition | attachment; filename="report.pdf"; filename*=UTF-8''report.pdf | 指示瀏覽器彈出「另存新檔」對話框,filename* (RFC 5987) 解決中文檔名跨瀏覽器亂碼。 |
| Content-Type | application/octet-stream 或具體 MIME (application/pdf) | 告知瀏覽器檔案類型,octet-stream 強制下載而非瀏覽器內開啟。 |
| Content-Length | 1048576 | 檔案總位元組數,支援進度條、斷點續傳。 |
| Accept-Ranges | bytes | 宣支援 Range 請求 (斷點續傳)。 |
| Cache-Control | private, max-age=0, must-revalidate | 私有快取、不共用、需重新驗證,防止 Proxy 快取敏感檔案。 |
| Content-Transfer-Encoding | binary | 標示傳輸編碼為二進位。 |
package com.example.util;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public final class FileDownloadUtil {
private static final int BUFFER_SIZE = 8192; // 8KB 緩衝區
private FileDownloadUtil() {}
/**
* 發送檔案下載回應 (支援 Range 斷點續傳)
* @param request HTTP 請求 (用於讀取 Range Header)
* @param response HTTP 回應
* @param file 伺服器端實體檔案
* @param downloadName 下載時顯示的檔名 (支援中文)
* @throws IOException
*/
public static void download(HttpServletRequest request, HttpServletResponse response,
File file, String downloadName) throws IOException {
if (!file.exists() || !file.isFile()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
long fileLength = file.length();
String mimeType = getServletContext().getMimeType(file.getName());
if (mimeType == null) mimeType = "application/octet-stream";
// 1. 處理檔名編碼 (RFC 5987 + 相容舊瀏覽器)
String encodedName = encodeFileName(downloadName, request.getHeader("User-Agent"));
// 2. 設定通用標頭
response.setContentType(mimeType);
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedName + "\"; filename*=UTF-8''" + encodedName);
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
response.setHeader("Content-Transfer-Encoding", "binary");
// 3. 處理 Range 請求 (斷點續傳 / 多執行緒下載)
String rangeHeader = request.getHeader("Range");
long start = 0, end = fileLength - 1;
if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
String[] ranges = rangeHeader.substring(6).split("-");
try {
start = Long.parseLong(ranges[0]);
if (ranges.length > 1 && !ranges[1].isEmpty()) end = Long.parseLong(ranges[1]);
} catch (NumberFormatException ignored) { /* 忽略無效 Range,傳完整檔案 */ }
// 邊界修正
if (start >= fileLength) start = 0;
if (end >= fileLength) end = fileLength - 1;
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206
response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
} else {
response.setStatus(HttpServletResponse.SC_OK); // 200
}
long contentLength = end - start + 1;
response.setHeader("Content-Length", String.valueOf(contentLength));
// 4. 串流傳輸 (NIO FileChannel transferTo 零拷貝,或傳統 BufferedInputStream)
try (RandomAccessFile raf = new RandomAccessFile(file, "r");
OutputStream out = response.getOutputStream()) {
raf.seek(start);
long remaining = contentLength;
byte[] buffer = new byte[BUFFER_SIZE];
int read;
while (remaining > 0 && (read = raf.read(buffer, 0, (int) Math.min(BUFFER_SIZE, remaining))) != -1) {
out.write(buffer, 0, read);
remaining -= read;
out.flush(); // 及時刷新,避免大檔案緩衝區積壓
}
}
// 輸出完成,Container 會自動提交回應
}
// 針對不同瀏覽器編碼檔名
private static String encodeFileName(String fileName, String userAgent) {
try {
String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
.replace("+", "%20") // 空格編碼為 %20 而非 +
.replace("*", "%2A")
.replace("%7E", "~");
// 現代瀏覽器支援 filename*,舊版 IE/Edge 需 filename 參數
// 此處統一返回 UTF-8 編碼字串,由呼叫端組裝雙標頭
return encoded;
} catch (Exception e) {
return "download"; // 兜底
}
}
// 取得 ServletContext (需在 Servlet/JSP 環境中注入或靜態持有)
private static jakarta.servlet.ServletContext getServletContext() {
// 實際專案中可透過 ServletContextListener 初始化靜態持有
// 或從 request.getServletContext() 取得
throw new UnsupportedOperationException("需在 Web 環境注入 ServletContext");
}
}
// DownloadServlet.java
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
private static final String BASE_DIR = "/data/uploads/";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String fileId = req.getParameter("id"); // 從資料庫查詢實際路徑與原始檔名
// 假設查詢結果
String storedPath = BASE_DIR + fileId + ".pdf";
String originalName = "2024年度報告_中文版.pdf";
File file = new File(storedPath);
FileDownloadUtil.download(req, resp, file, originalName);
}
}
<a href="<%= request.getContextPath() %>/download?id=report_2024">下載 2024 年度報告</a>
FileChannel.transferTo() 直接在核心態搬移資料,減少用戶態/核心態切換與記憶體拷貝。
try (FileChannel fc = raf.getChannel();
WritableByteChannel outCh = Channels.newChannel(response.getOutputStream())) {
fc.transferTo(start, contentLength, outCh);
}
req.startAsync() + 獨立執行緒池傳輸,釋放容器執行緒處理其他請求。file.getCanonicalPath().startsWith(BASE_DIR_CANONICAL),嚴禁直接信任請求參數拼接路徑。檔案下載看似簡單,實則涉及 HTTP 協定細節 (Range/Content-Range/206)、檔名編碼跨瀏覽器相容、大檔案記憶體控制、安全路徑驗證、頻寬保護等工程細節。封裝通用 FileDownloadUtil、配合 NIO 零拷貝與對象儲存直連架構,可構建高效、安全、可擴展的下載服務。