MaintainAction.java 完整代碼
package tester.business.maitain;
import tclcc.tester.util.Selector;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.util.*;
import org.apache.struts.upload.FormFile;
import java.io.*;
public class MaintainAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
MaintainForm maintainForm = (MaintainForm) form;
TrainPlanDAO trainPDAO = new TrainPlanDAO();
Trainplan trainPlan = maintainForm.getTrainPlan();
FormFile theFile = maintainForm.getTheFile1();
String p_accessory = theFile.getFileName();
try {
InputStream stream = theFile.getInputStream();
String filePath = request.getRealPath("/");
OutputStream bos = new FileOutputStream(filePath + "\\sub\\" + theFile.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
} catch (Exception e) { System.err.print(e); }
try {
trainPlan.setP_accessory(p_accessory);
trainPDAO.addTrainPlan(trainPlan);
System.out.println("success");
} catch (Exception ex) {}
request.setAttribute("trainPlain", trainPlan);
return mapping.findForward("trainplanCreated");
}
}
流程解析
- 從
MaintainForm 取得 Trainplan 與上傳檔案 FormFile。
- 讀取檔案輸入流,寫入伺服器磁盤
{contextRoot}/sub/{filename}。
- 設定附件檔名至
Trainplan,調用 DAO 入庫。
- 將
Trainplan 放入 Request 屬性 trainPlain,轉向 trainplanCreated(對應 veiwtrainplan.jsp)。
注意事項
- 路徑分隔符在 Windows 下使用
\\,跨平台建議用 File.separator。
- 缺乏檔案類型、大小驗證,生產環境需加強。
- 異常吞沒(
catch {})會隱藏錯誤,建議記錄日誌並返回錯誤頁。