在企業級 Web 應用中,檔案附件的管理是常見需求。本文介紹一個名為 FileKeeper 的 Servlet 工具類,封裝了檔案的上傳、下載、刪除與路徑轉換功能,採用 JSP SmartUpload 元件處理多部分表單資料,適用於早期 J2EE 專案。
類別靜態區塊從 config.properties 讀取 attachmentpath 作為檔案儲存根目錄:
static {
base_dir = PropertiesReader.getConfigValue("attachmentpath");
}
所有相對路徑皆以此為基準,確保部署遷移時只需修改設定檔。
getRelativePath()將絕對路徑轉換為相對於 base_dir 的路徑,統一使用反斜線並轉小寫比對,解決跨平台路徑分隔符差異:
public static String getRelativePath(File abs_path) {
String fullpath = abs_path.getAbsolutePath().replaceAll("/","\\\\").toLowerCase();
String new_base_dir = base_dir.replaceAll("/","\\\\").toLowerCase();
int i = fullpath.indexOf(new_base_dir);
return (i < 0) ? fullpath : fullpath.substring(i);
}
upload()支援自動重命名(避免衝突)與指定相對目錄:
rename=true,使用 File.createTempFile("sys", "", dir) 產生唯一檔名public static String upload(com.JSPsmart.upload.File for_upload,
String relative_dir, boolean rename) {
// 參數檢查與路徑正規化
// 目錄建立
// 檔案儲存邏輯
// 異常處理與日誌記錄
}
download() 與 doGet()download(String relative_path):回傳 FileInputStream,供外部程式讀取doGet():HTTP 端點,支援 path、filename、mime 參數,設定 Content-Disposition: attachment 觸發瀏覽器下載串流輸出採用 1KB 緩衝區逐塊寫入 response.getOutputStream(),避免大檔案記憶體溢位。
delete()簡單封裝 File.delete(),自動補齊前導反斜線,僅刪除檔案不刪除目錄。
web.xml 註冊 Servlet,映射如 /filekeeper/*config.properties 的 attachmentpath 指向可寫入目錄enctype="multipart/form-data" 表單/filekeeper?path=relative/path&filename=display_name&mime=application/pdf若專案使用 Spring Boot 或 Jakarta EE 9+,建議改用:
MultipartFile + StorageService 抽象介面Content-Disposition 標準化下載回應FileKeeper 展示了早期 Java Web 檔案處理的典型模式:集中管理儲存路徑、統一異常處理、提供 HTTP 端點。雖然技術棧已老舊,但其設計思想——關注點分離、配置外部化、串流式傳輸——在現代架構中依然適用。