承接上篇,本文定義 MaintainForm 繼承 ActionForm,封裝三個 FormFile 屬性對應前端 ``,並示範如何整合業務物件 Trainplan 實現表單資料與檔案並行處理。
package tester.business.maintain;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import org.apache.struts.upload.*;
public class MaintainForm extends ActionForm {
// 業務資料委託給 Trainplan
private Trainplan trainPlan = new Trainplan();
// 三個檔案上傳欄位
private FormFile theFile1;
private FormFile theFile2;
private FormFile theFile3;
// Trainplan 代理存取器
public String getP_title() { return trainPlan.getP_title(); }
public void setP_title(String p_title) { trainPlan.setP_title(p_title); }
public Trainplan getTrainPlan() { return trainPlan; }
public void setTrainPlan(Trainplan tp) { this.trainPlan = tp; }
// FormFile 存取器
public FormFile getTheFile1() { return theFile1; }
public void setTheFile1(FormFile f) { this.theFile1 = f; }
public FormFile getTheFile2() { return theFile2; }
public void setTheFile2(FormFile f) { this.theFile2 = f; }
public FormFile getTheFile3() { return theFile3; }
public void setTheFile3(FormFile f) { this.theFile3 = f; }
@Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest req) {
return null; // 實際專案加入檔案大小、類型、必填驗證
}
@Override public void reset(ActionMapping mapping, HttpServletRequest req) {
// 重置檔案欄位
theFile1 = theFile2 = theFile3 = null;
}
}
<html:form action="/maintain" enctype="multipart/form-data">
<html:text property="trainPlan.p_title"/>
<html:file property="theFile1"/>
<html:file property="theFile2"/>
<html:file property="theFile3"/>
<html:submit/>
</html:form>
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse res) {
MaintainForm mf = (MaintainForm) form;
// 1. 取得業務資料
Trainplan tp = mf.getTrainPlan();
// 2. 處理每個上傳檔
for (FormFile ff : new FormFile[]{mf.getTheFile1(), mf.getTheFile2(), mf.getTheFile3()}) {
if (ff != null && ff.getFileSize() > 0) {
String fileName = ff.getFileName();
InputStream is = ff.getInputStream();
// 儲存至磁碟/資料庫/雲端儲存
// ...
ff.destroy(); // 釋放暫存檔
}
}
return mapping.findForward("success");
}
<controller maxFileSize="10M" tempDir="/tmp/struts-upload"/>
<action path="/maintain"
type="tester.business.maintain.MaintainAction"
name="maintainForm"
scope="request"
input="/maintain.jsp">
<forward name="success" path="/list.do"/>
</action>
enctype="multipart/form-data" 必須設定,否則 FormFile 為 null。controller maxFileSize 限制單檔上限,超過拋 IOException。tempDir 需具備寫入權限。FormFile.destroy() 釋放磁碟空間。MultipartFile 或 Servlet 3.0 @MultipartConfig。