描述:Struts2文件上传是通过使用Commons-fileupload实现的,struts2通过拦截器org.apache.struts2.interceptor.FileUploadInterceptor实现。
JSP页面
<form action="upload.action" method="post" enctype="multipart/form-data"> 文件1:<input type="file" name="file"/><br/> <input type="submit" value="上传"/> </form>
Action代码,需要注意的是Action代码中三个属性的名称
public class UploadAction { //file属性名和表单域名相同 类型为File private File file; //上传文件名 属性名=表单域名+FileName private String fileFileName; //上传文件类型 属性名 =表单域名+ContentType private String fileContentType; public String upload() { String path = ServletActionContext.getServletContext().getRealPath("/upload"); try { FileUtils.copyFile(file, new File(path,fileFileName)); return Action.SUCCESS; } catch (IOException e) { e.printStackTrace(); } return Action.ERROR; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFileContentType() { return fileContentType; } public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; } }
strust.xml文件配置
<struts> <!-- 配置临时文件存放地址 --> <constant name="struts.multipart.saveDir" value="c:\"/> <!-- 配置文件上传的总大小 --> <constant name="struts.multipart.maxSize" value="60000000"/> <package name="default" namespace="/" extends="struts-default"> <action name="upload" class="com.whb.action.UploadAction" method="upload"> <result>/success.jsp</result> <result name="error">/error.jsp</result> <interceptor-ref name="fileUpload"> <!-- 配置单个文件上传的大小 --> <param name="maximumSize">60000000</param> </interceptor-ref> <!-- 注意在手动调用文件上传拦截器后,需要调用拦截器栈,不然不会对值进行装配 --> <interceptor-ref name="basicStack"></interceptor-ref> </action> </package> </struts>