檔案上傳核心在於解析 multipart/form-data 請求體。本 Bean 手工解析請求輸入流,提取檔案內容並寫入磁碟。適合學習原理,生產環境建議使用 Apache Commons FileUpload 或 Servlet 3.0 @MultipartConfig。
package yuanyifileup;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.PageContext;
public class yuanyifileup {
private ServletRequest request;
private ServletResponse response;
private ServletConfig config;
private ServletInputStream DATA;
private int FormSize;
private File f1;
private FileOutputStream os;
private DataInputStream is;
private String filename;
private byte[] b;
private byte t;
private boolean flag = false;
public yuanyifileup() {}
// 從 Servlet 初始化
public void initialize(ServletConfig config, HttpServletRequest request, HttpServletResponse response) throws IOException {
this.request = request; this.response = response; this.config = config;
DATA = request.getInputStream();
FormSize = request.getContentLength();
}
// 從 JSP PageContext 初始化
public void initialize(PageContext pageContext) throws IOException {
request = pageContext.getRequest();
response = pageContext.getResponse();
config = pageContext.getServletConfig();
DATA = request.getInputStream();
FormSize = request.getContentLength();
}
// 設定儲存路徑與檔名
public boolean setFilename(String s) {
try {
f1 = new File(s);
os = new FileOutputStream(f1);
return true;
} catch (IOException e) { return false; }
}
// 讀取整個請求體到位元組陣列
public void getByte() {
int i = 0;
try {
is = new DataInputStream(DATA);
b = new byte[FormSize];
while (true) {
try {
t = is.readByte();
b[i++] = t;
} catch (EOFException e) { break; }
}
is.close();
} catch (IOException e) {}
}
// 解析 multipart 並儲存檔案
public boolean save() {
int i = 0, start1 = 0, start2 = 0;
String temp = "";
if (!flag) { getByte(); flag = true; }
try {
temp = new String(b, "ISO8859_1");
} catch (UnsupportedEncodingException e) { return false; }
// 尋找檔案部分起始位置
start1 = temp.indexOf("image/");
if (start1 == -1) return false; // 非圖片或格式異常
temp = temp.substring(start1);
start1 = temp.indexOf("\r\n\r\n");
if (start1 == -1) return false;
temp = temp.substring(start1 + 4); // 跳過雙 CRLF
// 尋找結束邊界
start2 = temp.indexOf("\r\n--");
if (start2 != -1) temp = temp.substring(0, start2);
try {
byte[] img = temp.getBytes("ISO8859_1");
for (i = 0; i < img.length; i++) os.write(img[i]);
os.close();
return true;
} catch (IOException e) { return false; }
}
}
<%@ page import="yuanyifileup.yuanyifileup" %>
<%
yuanyifileup up = new yuanyifileup();
up.initialize(pageContext);
// 設定儲存完整路徑 (實際專案請驗證路徑安全性)
up.setFilename("D:/uploads/" + System.currentTimeMillis() + ".jpg");
boolean ok = up.save();
out.println(ok ? "上傳成功" : "上傳失敗");
%>
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="上傳">
</form>
| 限制 | 說明 | 改進 |
|---|---|---|
| 僅支援單檔上傳 | 未解析多部分邊界 | 解析 boundary,循環處理每個 part |
| 硬編碼尋找 "image/" | 只能上傳圖片,且依賴 Content-Type 順序 | 正規解析 Content-Disposition header 取得檔名 |
| 一次性讀取整個請求體到記憶體 | 大檔案會 OOM | 邊讀邊寫,或使用臨時檔案緩衝 |
| 無檔案大小、類型驗證 | 安全風險 | 前後端雙重驗證 |
| 字元編碼固定 ISO8859_1 | 中文檔名亂碼 | 依 RFC 5987 / Servlet 規範處理編碼 |