strutst2檔案上傳配置
<constant name="struts.custom.i18n.resources" value="myResource"/>
struts2.xml檔案中的配置 使用國際化資源
jsp頁面
<body>
<form action="action/saveFile_B1ction" name="fm" method ="post" enctype="multipart/form-data">
上傳檔案<input type="file" name="upload"/>
<input type="submit" value="上傳"/>
</form>
</body>
</html>
編寫action類
package hu.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileAction extends ActionSupport {
private File[] upload;
private String[] uploadFileName;
private String[] uploadContextType;
private String path;
public String saveFile() {
// TODO Auto-generated method stub
path = ServletActionContext.getServletContext().getRealPath("upload");
try {
for (int i = 0; i < upload.length; i++) {
FileUtils.copyFile(upload[i], new File(path+"/"+uploadFileName[i]));
}
System.out.println("ad");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String[] getUploadContextType() {
return uploadContextType;
}
public void setUploadContextType(String[] uploadContextType) {
this.uploadContextType = uploadContextType;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
新增action的配置檔案
<package name="action" extends="struts-default" namespace="/action">
<action name="*_B1ction" class="hu.action.FileAction" method="{1}">
<result name="success">/filesuccess.jsp</result>
<result name="input">/error.jsp</result>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/bmp,image/gif</param>
<!-- <param name="allowedExtensions">.bmp,.gif,.jpg</param> -->
<param name="maximumSize ">10000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
</action>
<package/>
錯誤頁面: <s:fielderror></s:fielderror>
專案路徑下 myResource_zh_CN.properties
struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u7C7B\u578B\u9519\u8BEF\uFF01
struts.messages.error.file.extension.not.allowed=\u6587\u4EF6\u6269\u5C55\u540D\u4E0D\u6B63\u786E\uFF01
struts.messages.error.uploading=\u4E0A\u4F20\u901A\u7528\u9519\u8BEF\uFF01
struts.messages.error.file.too.large=\u4E0A\u4F20\u6587\u4EF6\u8FC7\u5927\uFF01
userName=\u7528\u6237\u540D\u4E0D\u5408\u6CD5
uploadFile.message=upload File One: