首页 > 代码库 > struts2文件上传下载

struts2文件上传下载

之前没写过struts2上传下载,只是知道大概怎么搞,最近项目中用到,正巧赶上了,编码过程中遇到过一些问题,如上传文件类型,中文乱码,兼容性问题等,不过都一一解决了,下面附上自己的代码。以便将来查阅...

也希望这篇随便能够帮助很多朋友少走些弯路把!

1.文件上传

首先是jsp页面的代码

在jsp页面中定义一个上传标签

1 <tr>
2      <td align="right" bgcolor="#F5F8F9"><b>附件:</b></td>
3      <td bgcolor="#FFFFFF">
4      <input type="file" name="upload" />
5      </td>
6      <td bgcolor="#FFFFFF">&nbsp;</td>
7 </tr>

然后是BaseAction中定义的相关属性其它的就省略了(也可定义在自己的Action,换下访问修饰符即可)

 1 /**
 2 *Action基类
 3 **/
 4 public class BaseAction extends ActionSupport {
 5 
 6     protected List<File> upload;
 7     protected List<String> uploadContentType; //文件类型
 8     protected List<String> uploadFileName;    //文件名
 9     protected String savePath;                //保存路径
10 
11 }

然后是Action中的一个上传方法,代码如下:

 1   /**
 2   * 8.上传附件
 3   * @param upload
 4   */
 5   public void uploadAccess(List<File> upload){
 6         try {
 7             if (null != upload) {
 8                 for (int i = 0; i < upload.size(); i++) {
 9                     String path = getSavePath() + "\\"+ getUploadFileName().get(i);
10                     System.out.println(path);
11                     item.setAccessory(getUploadFileName().get(i));
12                     
13                     FileOutputStream fos = new FileOutputStream(path);
14                     FileInputStream fis = new FileInputStream(getUpload().get(i));
15                     byte[] buffer = new byte[1024];
16                     int len = 0;
17                     while ((len = fis.read(buffer)) > 0) {
18                         fos.write(buffer, 0, len);
19                     }
20                     fis.close();
21                     fos.close();
22                 }
23             }
24         } catch (Exception e) {
25             logger.error("上传附件错误。", e);
26         }
27     }

接着是我的struts2.xml文件

 1 <action name="itemRDAction_*" class="itemRDAction" method="{1}">
 2      <param name="savePath">e:\upload</param>
 3      <interceptor-ref name="defaultStack">
 4            <param name="fileUpload.allowedTypes">
 5                application/octet-stream,image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel
 6            </param>
 7            <param name="fileUpload.maximumSize">8000000</param>
 8      </interceptor-ref>
 9      <result name="show_item_rd_upd">  /WEB-INF/jsp/page_item/updItem_rd.jsp</result>
10      <result name="show_item_rd_list"> /WEB-INF/jsp/page_item/listItem_rd.jsp</result>
11      <result name="show_item_rd_push"> /WEB-INF/jsp/page_item/pushItem_rd.jsp</result>
12 </action>

savePath为保存路径,fileUpload.allowedTypes 用来限制上传文件类型 fileUpload.maximumSize 文件大小限制

2.文件下载

首先是页面中的下载链接

 1 <tr>
 2    <td width="20%" align="right" bgcolor="#F5F8F9"><b>附件:</b></td>
 3    <td width="40%" bgcolor="#FFFFFF">
 4    <div style="width:355px; float: left;">${item.accessory}</div>
 5        <c:if test="${!empty item.accessory}">
 6            <div class="btn_img" style="float: left;"><a style="color: black; text-decoration: none;" href="download.action?filename=${item.accessory}">下载</a></div>
 7        </c:if>
 8    </td>
 9    <td width="40%" bgcolor="#FFFFFF">&nbsp;</td>
10 </tr> 

接着是DownloadAction的代码:

 1 /**
 2  * DownloadAction
 3  * 
 4  * @author zhaoxz
 5  * 
 6  */
 7 @Controller("downloadAction")
 8 @Scope("prototype")
 9 public class DownloadAction extends BaseAction {
10 
11     /**
12      * 
13      */
14     private static final long serialVersionUID = -4278687717124480968L;
15 
16     private static Logger logger = Logger.getLogger(DownloadAction.class);
17 
18     private String filename;
19     private InputStream inputStream;
20     private String savePath;
21     private String mimeType;
22 
23     public InputStream getInputStream() {
24         try {
25             String path = getSavePath() + "//"+ new String(filename.getBytes("ISO8859-1"), "utf-8");
26             System.out.println(path);
27             mimeType = ServletActionContext.getServletContext().getMimeType(path)+ ";charset=UTF-8";
28             inputStream = new FileInputStream(path);
29             String agent = request.getHeader("USER-AGENT");
30             System.out.println(agent);
31             if (null != agent) {
32                 if (-1 != agent.indexOf("Firefox")) {// Firefox
33                     mimeType = mimeType.replace("UTF-8", "ISO8859-1");
34                 } else {// IE7+ Chrome
35                     System.out.println("IE,Chrome");
36                     filename = new String(filename.getBytes("ISO8859-1"),"utf-8");
37                     filename = java.net.URLEncoder.encode(filename, "UTF-8");
38                 }
39             }
40         } catch (Exception e) {
41             logger.error("下载文件信息出错。", e);
42         }
43         if (null == inputStream) {
44             System.out.println("getResource error");
45         }
46         return inputStream;
47     }
48 
49     public void setInputStream(InputStream inputStream) {
50         this.inputStream = inputStream;
51     }
52 
53     @Override
54     public String execute() throws Exception {
55         return SUCCESS;
56     }
57 
58     /*************************** get set ******************************/
59     public String getSavePath() {
60         return this.savePath;
61     }
62 
63     public void setSavePath(String savePath) {
64         this.savePath = savePath;
65     }
66 
67     public String getFilename() {
68         return filename;
69     }
70 
71     public void setFilename(String filename) {
72         this.filename = filename;
73     }
74 }

然后是它的struts2.xml文件:

1 <action name="download" class="downloadAction">
2     <param name="savePath">E:/upload</param>
3     <result type="stream">
4           <param name="contentType">${mimeType}</param>
5           <param name="contentDisposition">attachment;filename="${filename}"</param>
6           <param name="inputName">inputStream</param>
7     </result>
8 </action>

下载的话注意下编码格式基本应该就没什么问题了..希望能帮的你们!本人年纪比较小是个小白...要学的东西很多,有什么需要改进的地方还请各位明示!在此谢过了。