Struts 1 雖然歷史悠久,但其文件上傳機制通過封裝 Commons FileUpload,提供了相對簡潔的 API。本文通過完整示例解析 Struts 1 文件上傳的核心組件、配置要點與代碼實現。
<input type="file">,property 對應 ActionForm 屬性。getInputStream(), getFileName(), getFileSize() 等方法。<%@ taglib uri="https://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html:form action="/jsp/upload.do" method="post" enctype="multipart/form-data">
<html:file property="photo"/>
<html:submit value="上傳"/>
</html:form>
package com.zyy.struts.form;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm {
private FormFile photo;
// getter/setter 省略
}
package com.zyy.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class IPTimeStamp {
private String ip;
public IPTimeStamp(String ip) { this.ip = ip; }
public String getIPTimeRand() {
StringBuffer buf = new StringBuffer();
if (ip != null) {
for (String s : ip.split("\\.")) buf.append(addZero(s, 3));
}
buf.append(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
for (int i=0; i<3; i++) buf.append(new Random().nextInt(10));
return buf.toString();
}
private String addZero(String str, int len) {
StringBuffer s = new StringBuffer(str);
while (s.length() < len) s.insert(0, "0");
return s.toString();
}
}
package com.zyy.struts.action;
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import com.zyy.struts.form.UploadForm;
import com.zyy.util.IPTimeStamp;
public class UploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UploadForm uploadForm = (UploadForm) form;
FormFile photo = uploadForm.getPhoto();
// 1. 生成唯一文件名:IP+時間戳+隨機數 + 原始擴展名
String ext = photo.getFileName().substring(photo.getFileName().lastIndexOf("."));
String fileName = new IPTimeStamp(request.getRemoteAddr()).getIPTimeRand() + ext;
// 2. 目標目錄:應用根目錄下的 upload 資料夾
String realPath = getServlet().getServletContext().getRealPath("/") + "upload" + File.separator;
File dir = new File(realPath);
if (!dir.exists()) dir.mkdirs();
// 3. 流式寫入
File outFile = new File(realPath + fileName);
try (InputStream in = photo.getInputStream();
OutputStream out = new FileOutputStream(outFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len);
}
return null; // 無需跳轉,或按需返回 mapping.findForward("success")
}
}
<form-beans>
<form-bean name="uploadForm" type="com.zyy.struts.form.UploadForm"/>
</form-beans>
<action-mappings>
<action path="/jsp/upload"
type="com.zyy.struts.action.UploadAction"
name="uploadForm"
scope="request"
input="/jsp/sh.jsp">
</action>
</action-mappings>
method="post"enctype="multipart/form-data"<input type="file"> 欄位getInputStream():獲取文件內容流getFileName():原始文件名(含路徑,需處理)getFileSize():文件大小(字節)getContentType():MIME 類型destroy():釋放臨時文件資源(重要!)Struts 1 / Commons FileUpload 預設將小文件存內存,大文件寫臨時目錄。可在 struts-config.xml 的 <controller> 中配置:
<controller maxFileSize="10M" tempDir="/tmp/upload" />
示例採用 IP+毫秒時間戳+3位隨機數 策略,極大降低衝突概率。生產環境建議加入 UUID 或分布式 ID。
new String(name.getBytes("ISO-8859-1"), "UTF-8") 轉碼。maxFileSize、Tomcat maxPostSize、磁盤空間。FormFile.destroy()。Struts 1 文件上傳本質是對 Commons FileUpload 的封裝,核心流程為:JSP 表單 → FormFile 封裝 → Action 流式存儲。掌握 FormFile API、enctype 設置、文件命名策略與資源釋放是穩健實現的關鍵。雖然 Struts 1 已退出歷史舞台,但其設計思想對理解現代框架(Spring MVC, Struts 2)文件上傳機制仍有參考價值。