手動解析 multipart/form-data 請求,程式碼複雜但可控性高。核心類別:DiskFileItemFactory、ServletFileUpload、FileItem。
// 關鍵步驟
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxSize);
List<FileItem> items = upload.parseRequest(request);
// 區分一般參數與檔案欄位
// 手動處理輸入/輸出流儲存檔案
SmartUpload 為 smartupload.jar,放入 classpath 或 TOMCAT_HOME/lib 即可使用。特點:
<!-- HTML 表單 -->
<form action="smartupload_demo01.jsp" method="post" enctype="multipart/form-data">
圖片<input type="file" name="pic">
<input type="submit" value="上傳">
</form>
// JSP 處理
<%@ page import="com.jspsmart.upload.*" %>
<%
SmartUpload smart = new SmartUpload();
smart.initialize(pageContext);
smart.upload();
smart.save("upload"); // 儲存至 upload 目錄
out.print("上傳成功");
%>
<%@ page import="com.jspsmart.upload.*" %>
<%@ page import="com.zhou.study.IPTimeStamp" %>
<%
SmartUpload smart = new SmartUpload();
smart.initialize(pageContext);
smart.upload();
IPTimeStamp its = new IPTimeStamp("192.168.1.1");
for (int x = 0; x < smart.getFiles().getCount(); x++) {
String ext = smart.getFiles().getFile(x).getFileExt();
String fileName = its.getIPTimeRand() + "." + ext;
smart.getFiles().getFile(x).saveAs(
getServletContext().getRealPath("/") + "upload" + File.separator + fileName);
}
out.print("上傳成功");
%>
package com.zhou.study;
public class IPTimeStamp {
private SimpleDateFormat sdf;
private String ip;
public String getIPTimeRand() {
StringBuffer buf = new StringBuffer();
if (ip != null) {
String[] s = ip.split("\\.");
for (String part : s) buf.append(addZero(part, 3));
}
buf.append(getTimeStamp());
Random r = new Random();
for (int i = 0; i < 3; i++) buf.append(r.nextInt(10));
return buf.toString();
}
// 格式:IP段(3碼) + 時間戳(yyyyMMddHHmmssSSS) + 3位隨機數
// 例:19216800100120240109143045123456
}
upload 資料夾maxSize 參數