Struts2通过FileUploadInterceptor拦截器实现文件上传,demo如下:
先上struts.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd" >
<struts>
<package name="up" namespace="/u" extends="struts-default">
<action name="uploadAction" class="com.wxhl.upload.UploadAction" method="upLoad">
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedExtensions">txt,jpg</param>
<param name="fileUpload.allowedType">text/plain,image/jpeg</param>
</interceptor-ref>
<result name="UP">/updown/index.jsp</result>
<result name="input">/updown/error.jsp</result>
</action>
</package>
</struts>其次是jsp页面:
<body>
<div style="text-align:center">
<h1>文件上传页面</h1>
<form action="${pageContext.request.contextPath}/u/uploadAction"
method="post" enctype="multipart/form-data">
用户名:<input type="text" name="userName"/>
文件名:<input type="file" name="file1"/>
<input type="submit" value="上传"/>
</form>
</div>
</body>
注意:form中必须设置enctype的值为multipart/form-data-
然后是action类:
public class UploadAction extends ActionSupport{
private static final long serialVersionUID = -2070240561299671465L;
//获取文件对应表单<input type="file" name="file1"/>
private File file1;
//获取文件名字
private String file1FileName;
//获取文件类型
private String file1ContentType;public File getFile1() { return file1; } public void setFile1(File file1) { this.file1 = file1; } public String getFile1FileName() { return file1FileName; } public void setFile1FileName(String file1Name) { this.file1FileName = file1Name; } public String getFile1ContentType() { return file1ContentType; } public void setFile1ContentType(String file1Type) { this.file1ContentType = file1Type; } public String upLoad(){ //获取文件存放路径 String path = ServletActionContext.getServletContext().getRealPath("/upload"); //System.out.println(path); //新建文件 File newFile = new File(path,file1FileName); //复制文件 try { FileUtils.copyFile(file1, newFile); } catch (IOException e) { e.printStackTrace(); } return "UP"; } }
注意:此处File对象的名字必须与文件名的name保持一直,两者只有一个字段file1保持一直,这就是FileUploadInterceptor的功劳
- 总结
你所要做的只是按照一定的样式命名这三个字段的set方法,而字段名可以任意命名。第一个File类型的字段的set方法还是以常规的方式命名,另两个String类型的字段(文件名和文件类型)的set方法,必须分别以“set+File字段的名字+FileName”和“set+File字段的名字+ContentType”来命名。