struts2没有提供自己的请求解析器,也就是说,struts2不会自己去处理multipart/form-data的请求,它需要调用其他请求解析器,将HTTP请求中的表单域解析出来,但struts2在原有的上传解析器上作了进一步封装,更进一步简化了文件上传,Struts2的struts.properties配置文件中,配置struts2的上传文件解析器struts.multipart.parser=jakarta(srtuts2默认),也可以设置为常用的cos,pell等。
struts2实现上传下载所必须的2个jar包:commons-fileupload-xxx.jar和commons-io-xxx.jar。
一、文件上传
1. 单文件上传
(1)单文件上传表单视图:
- <body>
- <form action="/test/upload.action" enctype="multipart/form-data" method="post">
- <input name="uploadfile" type="file">
- <input type="submit" value="上传">
- </form>
- </body>
注意:表单必须设置enctype="multipart/form-data"和method="post"属性,否则上传会出错。
2. 单文件上传Action类
- /**
- * 文件上传类
- * @author Ye
- *
- */
- public class UploadAction extends ActionSupport{
- <!--获取上传文件,名称必须和表单file控件名相同-->
- private File uploadfile;
- <!--获取上传文件名,命名格式:表单file控件名+FileName(固定)-->
- private String uploadfileFileName;
- //获取上传文件类型,命名格式:表单file控件名+ContentType(固定)
- private String uploadfileContentType;
- ...//省略属性的getter、setter方法
- //方法一:使用FileUtils的copyFile来实现文件上传
- public String upload() throws IOException
- {
- //设置上传文件目录
- String realpath = ServletActionContext.getServletContext().getRealPath("/image");
- //判断上传文件是否为空
- if(uploadfile!=null)
- {
- //设置目标文件(根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例)
- File savefile = new File(realpath,uploadfileFileName);
- // 判断上传目录是否存在
- if(!savefile.getParentFile().exists())
- savefile.getParentFile().mkdirs();
- //把文件uploadfile 拷贝到 savefile 里,FileUtils类需要commons-io-x.x.x.jar包支持
- FileUtils.copyFile(uploadfile,savefile);
- //设置request对象值
- ActionContext.getContext().put("message", "上传成功!");
- }
- return "success";
- }
- //方法二:使用文件流来实现文件上传
- public String upload() throws IOException
- {
- FileOutputStream fos = new FileOutputStream("D:\\"+uploadfileFileName);
- FileInputStream fis = new FileInputStream(uploadfile);
- byte[] buffer = new byte[1024];
- int len = 0;
- while((len=fis.read(buffer))>0)
- {
- fos.write(buffer,0,len);
- }
- return "success";
- }
- }
注意:记得Action类要继承ActionSupport。
3. 配置struts.xml文件
- <package name="hello" namespace="/test" extends="struts-default">
- <action name="upload" class="action.UploadAction" method="upload">
- <!-- 在struts.xml文件中使用constant元素指定在全局的struts.properties文件中自定义出错信息,value值为*.properties类型的文件名 -->
- <constant name="struts.custom.i18n.resources" value="struts"></constant>
- <!-- 配置fileUpload的拦截器 -->
- <interceptor-ref name="fileUpload">
- <!-- 配置允许上传的文件类型 -->
- <param name="allowedTypes">image/bmp,image/gif,image/jpg</param>
- <!--配置允许上传文件的扩展名,如果有多个用","隔开 -->
- <param name="allowedExtensions">txt,excel,ppt</param>
- <!-- 配置允许上传的文件大小,最大为20k -->
- <param name="maximumSize">20480</param>