Struts 2 內建 fileUpload 攔截器 (基於 Apache Commons FileUpload),需確保類路徑包含:
commons-fileupload-1.3.x.jarcommons-io-2.x.jar
必須:enctype="multipart/form-data",<s:file> 的 name 屬性 (如 myFile) 決定 Action 中屬性名。
public class FileUploadAction extends ActionSupport {
private File myFile; // 上傳文件對象
private String myFileFileName; // 原始文件名
private String myFileContentType; // MIME 類型
// Getter/Setter 省略
public String execute() {
String saveDir = ServletActionContext.getServletContext().getRealPath("/upload");
File dest = new File(saveDir, myFileFileName);
try {
FileUtils.copyFile(myFile, dest); // commons-io
addActionMessage("上傳成功: " + myFileFileName);
} catch (IOException e) {
addActionError("上傳失敗: " + e.getMessage());
return ERROR;
}
return SUCCESS;
}
}
命名規則:屬性名、屬性名FileName、屬性名ContentType。
10485760
image/jpeg,image/png,application/pdf
/upload_result.jsp
/upload_form.jsp
參數說明:
maximumSize:字節單位,超過返回 input,字段錯誤鍵 struts.messages.error.file.too.large。allowedTypes:逗號分隔 MIME 類型,不匹配返回 input,錯誤鍵 struts.messages.error.content.type.not.allowed。allowedExtensions:可選,按擴展名過濾 (如 jpg,png,pdf)。
struts.messages.error.file.too.large=文件大小不能超過 {0} 字節
struts.messages.error.content.type.not.allowed=不支持的文件類型: {0}
// JSP
// 同名
// Action
private List files;
private List filesFileName;
private List filesContentType;
// 遍歷列表處理