Struts2实现文件上传

 

今天在群里看到一个朋友问struts2怎么实现文件上传,平时都只是在页面传值过来,还真没有实现过图片上传呢,于是我研究了研究,下面请看操作

实现文件上传必须导入的jar包commons-fileupload-1.2.2.jar  还有个commons-io-2.0.1.jar  这个jar文件主要是用里面的一个FileUtils类,看完之后就知道它的作用了。

web.xml的配置一样,这里不阐述了。
struts.xml内容:

struts.xml
 1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6 <struts>
7 <!-- Add packages here -->
8 <package name="default" namespace="/" extends="struts-default">
9 <action name="upload_*" method="{1}" class="UploadAction">
10 <result name="sucess">/sucess.jsp</result>
11 <result name="error">/error.jsp</result>
12 </action>
13 </package>
14 </struts>

form表单内容:

Form表单内容
1     <form action="upload_upload" enctype="multipart/form-data" method="post">
2 <input type="file" name="image" />
3 <input type="submit" value="upload">
4 </form>

关键的是UploadAction类的内容,请看代码:

UploadAction
 1 import java.io.File;
2 import java.io.IOException;
3
4 import org.apache.commons.io.FileUtils;
5 import org.apache.struts2.ServletActionContext;
6
7 public class UploadAction {
8 private File image;
9 private String imageFileName;
10
11 public File getImage() {
12 return image;
13 }
14
15 public void setImage(File image) {
16 this.image = image;
17 }
18
19 public String getImageFileName() {
20 return imageFileName;
21 }
22
23 public void setImageFileName(String imageFileName) {
24 this.imageFileName = imageFileName;
25 }
26
27 public String upload() {
28 String realpath = ServletActionContext.getServletContext().getRealPath(
29 "/image");
30 File file = new File(new File(realpath),imageFileName);
31 if (!file.getParentFile().exists())
32 file.getParentFile().mkdirs();
33 try {
34 FileUtils.copyFile(image, file);
35
36 return "sucess";
37 } catch (IOException e) {
38 e.printStackTrace();
39 return "error";
40 }
41 }
42
43 }

有几点要说明

private File image;
private String imageFileName;

image和表单提交过来的name一定要相同, imageFileName是获取传过来的文件名

FileUtils.copyFile(image, file); 就是将临时区的图片复制到指定的目录下,这样就实现了文件上传。

如果是多文件上传,改成

 private File[] image;
 private String[] imageFileName;

 form表单里面的file input的name都改成image即可。


posted @ 2012-03-14 17:12  Paul.Lau  阅读(285)  评论(0编辑  收藏  举报