JSP 原生不支援文件上傳,需借助第三方組件。SmartUpload(來自 jspsmart.com)功能完整、API 簡潔,支援檔案類型限制、大小控管、多檔上傳、資料庫二進位存儲,廣泛應用於早期 JSP 專案。本文提供從前端表單到後端處理、資料庫存儲的完整實作範例。
method="post":上傳檔案通常較大,GET 受 URL 長度限制。enctype="multipart/form-data":採用二進位多部分編碼傳輸。<input type="file" name="file">:檔案選擇欄位,可放置多個支援多檔上傳。<FORM action="upload.jsp" enctype="multipart/form-data" method="post">
<INPUT type="file" name="file" size="60"><br>
<INPUT type="file" name="file1" size="60"><br>
<INPUT type="text" name="text" size="60"><br>
<INPUT type="submit" value="Send" name="send">
</FORM>
SmartUpload su = new SmartUpload(); su.initialize(pageContext);su.setMaxFileSize(500 * 1024 * 1024);(500MB)su.upload();su.getFiles().getCount() 迴圈處理每個 File 物件。myFile.saveAs(path, SmartUpload.SAVE_PHYSICAL);FileInputStream 讀取檔案,配合 PreparedStatement.setBinaryStream() 存入 BLOB 欄位。// 核心片段
for (int i=0; i<su.getFiles().getCount(); i++) {
com.jspsmart.upload.File f = su.getFiles().getFile(i);
if (!f.isMissing()) {
String fileName = f.getFileName();
String savePath = getServletContext().getRealPath("/") + "jsp" + fileName;
f.saveAs(savePath, su.SAVE_PHYSICAL);
// 存入資料庫
FileInputStream fis = new FileInputStream(new File(savePath));
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO marklist (markname, password, marksize, markdate, MarkBody) VALUES (?,?,?,?,?)");
ps.setString(1, "aaa1");
ps.setString(2, "0000");
ps.setInt(3, f.getSize());
ps.setString(4, getDateTime());
ps.setBinaryStream(5, fis, (int)new File(savePath).length());
ps.executeUpdate();
}
}
SmartUpload 將檔案完整讀入記憶體再處理,超過 100MB 大檔易導致 OOM。現代專案建議改用 Apache Commons FileUpload(支援流式處理、臨時檔案閾值)或 Servlet 3.0 原生 @MultipartConfig + request.getPart(),更穩健且無第三方依賴。