SmartUpload 是經典的檔案上傳元件,支援大檔、多檔、進度條、檔案型別過濾。下面以 Servlet 為例示範完整上傳流程與關鍵配置。
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private static final String SAVE_PATH = "E:/public_html/java_root/NETDISK/WebRoot/NET_SPACE/1/我的音樂/";
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=gb2312");
PrintWriter out = resp.getWriter();
SmartUpload su = new SmartUpload();
su.setForcePhysicalPath(true); // 允許絕對路徑
su.setMaxFileSize(10_000_000); // 10MB 單檔上限
// su.setTotalMaxFileSize(20_000_000); // 總上限
// su.setAllowedFilesList("doc,txt,pdf"); // 白名單
// su.setDeniedFilesList("exe,bat,jsp,html"); // 黑名單
su.initialize(getServletConfig(), req, resp);
try {
su.upload(); // 解析 multipart 請求
} catch (SmartUploadException e) {
e.printStackTrace();
return;
}
// 讀取普通表單欄位
com.jspsmart.upload.Request sReq = su.getRequest();
String title = sReq.getParameter("dest");
// 逐檔儲存
for (int i = 0; i < su.getFiles().getCount(); i++) {
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if (file.isMissing()) continue;
try {
file.saveAs(SAVE_PATH + file.getFileName()); // 同名覆蓋,生產環境建議加 UUID 前綴
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
out.println("dest:" + title);
}
}
| 方法 | 用途 |
|---|---|
setForcePhysicalPath(true) | 允許 saveAs() 使用絕對路徑,預設 false 僅允許相對路徑 |
setMaxFileSize(bytes) | 單檔大小上限,超過拋出異常 |
setTotalMaxFileSize(bytes) | 整個請求總大小上限 |
setAllowedFilesList("ext,...") | 僅允許列表內副檔名(不含點) |
setDeniedFilesList("ext,...") | 禁止列表內副檔名,"" 代表無副檔名 |
SmartUpload 已停止維護,新專案建議改用 Apache Commons FileUpload 或 Servlet 3.0+ 內建 @MultipartConfig + request.getPart(),無第三方依賴、支援非阻塞 IO、整合 Spring MVC 更自然。