直接讀取 `ServletInputStream`,手工解析 `multipart/form-data` 格式:邊界分隔符、Header 區、檔案內容、結束邊界。教學價值高,生產環境請用成熟庫。
package linkman.helper;
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.ServletInputStream;
public class UpLoadBean {
private String savePath = null;
private String fileName = null;
private String separator = null;
private String errMsg = "正常返回";
private byte[] bt = new byte[4096];
private byte[] prebt = new byte[4096];
private int t = -1;
private long fileSize = -1;
private boolean userDefineFileName = false;
public UpLoadBean() { fileName = bringFileName(); }
public UpLoadBean(String savePath) { this.savePath = savePath; fileName = bringFileName(); }
// 自動生成檔名:yyyyMMddHHmmss
private String bringFileName() {
Calendar dt = Calendar.getInstance();
return "" + dt.get(Calendar.YEAR) + (dt.get(Calendar.MONTH)+1) + dt.get(Calendar.DAY_OF_MONTH)
+ dt.get(Calendar.HOUR_OF_DAY) + dt.get(Calendar.MINUTE) + dt.get(Calendar.SECOND);
}
public void setFileName(String fileName) { this.fileName = fileName; userDefineFileName = true; }
public String getFileName() { return fileName; }
public void setSavePath(String savePath) { this.savePath = savePath; }
public void setFileSize(long fileSize) { this.fileSize = fileSize; }
public String getErrorMessage() { return errMsg; }
private void setErrorMessage(String msg) { errMsg = msg; }
// 核心上傳邏輯
public boolean upLoad(HttpServletRequest request) throws Exception {
if (savePath == null) { setErrorMessage("未設置保存路徑"); return false; }
request.setCharacterEncoding("utf-8");
ServletInputStream in = request.getInputStream();
// 1. 讀取第一行獲取 boundary
t = in.readLine(bt, 0, bt.length);
if (t != -1) {
separator = new String(bt, 0, t).substring(0, 28); // 取前 28 字元作為分隔標記
t = -1;
}
// 2. 解析 Header 區,提取原始檔名中的副檔名
do {
t = in.readLine(bt, 0, bt.length);
String s = new String(bt, 0, t);
int idx = s.indexOf("filename=\"");
if (idx != -1) {
s = s.substring(idx + 10);
idx = s.indexOf("\"");
s = s.substring(0, idx);
idx = s.lastIndexOf(".");
if (!userDefineFileName) fileName += s.substring(idx); // 附加副檔名
t = -1;
}
} while (t != -1);
// 3. 跳過 Content-Type 行與空行
t = in.readLine(bt, 0, bt.length);
s = new String(bt, 0, t);
if (s.indexOf("Content-Type:") == -1) { setErrorMessage("上傳的不是檔案"); return false; }
in.readLine(bt, 0, bt.length); // 空行
t = -1;
// 4. 讀取檔案內容,直到遇到 boundary
FileOutputStream out = new FileOutputStream(savePath + "/" + fileName);
boolean state = true;
long transSize = 0;
try {
t = in.readLine(bt, 0, bt.length);
while (t != -1) {
s = new String(bt, 0, t);
// 檢測結束 boundary
if (s.length() > 28 && s.substring(0, 28).equals(separator)) break;
// 檔案大小限制
if (fileSize != -1 && transSize >= fileSize) throw new Exception("上傳檔案過大");
out.write(bt, 0, t);
transSize += t;
t = in.readLine(bt, 0, bt.length);
}
} catch (Exception e) {
state = false; out.close(); setErrorMessage(e.getMessage());
new File(savePath, fileName).delete(); // 清理未完成檔案
} finally {
if (state) out.close();
}
return state;
}
}
<%@ page import="linkman.helper.UpLoadBean" %>
<%
UpLoadBean up = new UpLoadBean(application.getRealPath("/upload"));
up.setFileSize(5 * 1024 * 1024); // 限制 5MB
boolean ok = up.upLoad(request);
if (ok) out.println("上傳成功,檔名:" + up.getFileName());
else out.println("上傳失敗:" + up.getErrorMessage());
%>
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="上傳">
</form>
| 環節 | 實作細節 | 潛在問題 |
|---|---|---|
| Boundary 解析 | 讀第一行,取前 28 字元 | Boundary 長度不固定,RFC 規定最多 70 字元,硬編碼 28 可能截斷 |
| 檔名提取 | 正則 `filename="..."` 取副檔名 | 不支援 RFC 5987 編碼檔名 (`filename*=utf-8''...`),中文檔名易亂碼 |
| 內容讀取 | `readLine` 逐行讀,遇 boundary 結束 | 二進位檔案可能無換行符,導致誤判 boundary 或讀取不全;`readLine` 效率低 |
| 編碼處理 | `new String(bt, "ISO8859_1")` | Header 區建議用 ASCII/ISO-8859-1,但檔案內容為二進位不應轉字串 |
| 記憶體 | 4KB 緩衝區,邊讀邊寫 | 尚可,但大檔案建議 64KB+ 緩衝 |
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
// Servlet 中使用
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File("/tmp")); // 臨時檔目錄
factory.setSizeThreshold(1024*1024); // 1MB 以上寫磁碟
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(10*1024*1024);
List items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = FilenameUtils.getName(item.getName());
item.write(new File("/uploads", fileName));
}
}
或 Servlet 3.0+ `@MultipartConfig` + `request.getPart()` (零依賴、容器級優化)。