struts2文件上传/下载(附源代码)

来源:互联网 发布:vnc mac版远程控制软件 编辑:程序博客网 时间:2024/04/28 16:32

转载自:http://blog.csdn.net/phantomes/article/details/8076832

struts2对于文件的操作提供很多便捷的地方,因此在项目中多少会涉及到它的使用,当然网上关于它的帖子也确实不少,清楚地,不清楚的,详细的,不详细的,都有很多,我也曾学到过很多热爱分享的同行们的帮助,在这里,我便按我自己思路,整理了下,写成这篇博文,并提供效果图和附件的下载。

首先,按老规矩,上效果图:


图一


图二


图三


图四


图五


然后我们看下这个项目的结构图:



第一步,新建一个web项目,我这里偷了个懒,upload/download,干脆就叫updownload,并加入struts2的相关jar包

第二步,新建com.action.UploadAction.java代码如下:

[java] view plaincopy
  1. package com.action;  
  2.   
  3. import java.io.File;  
  4. import java.util.List;  
  5.   
  6. import org.apache.commons.io.FileUtils;  
  7. import org.apache.struts2.ServletActionContext;  
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. public class UploadAction extends ActionSupport  
  12. {  
  13.     private static final long serialVersionUID = 1L;  
  14.       
  15.     private List<File>image;  
  16.     private List<String>imageContentType;  
  17.     private List<String>imageFileName;  
  18.       
  19.     @Override  
  20.     public String execute() throws Exception  
  21.     {  
  22.         String path=ServletActionContext.getServletContext().getRealPath("/images");  
  23.         System.out.println("保存路径为"+path);  
  24.          
[java] view plaincopy
  1. //文件拷贝   
  2.         if (image.size()>0)  
  3.         {  
  4.             File savedir=new File(path);  
  5.             if(!savedir.exists()) savedir.mkdirs();   
  6.             for (int i = 0; i < image.size(); i++)  
  7.             {  
  8.                 System.out.println("datas的个数"+image.size());  
  9.                 File saveFile=new File(savedir, imageFileName.get(i));  
  10.                 FileUtils.copyFile(image.get(i), saveFile);  
  11.             }  
  12.         }else {  
  13.             System.out.println("datas为空");  
  14.         }  
  15.           
[java] view plaincopy
  1. //文件拷贝的另一实现方式,还有一种是字节流去读取,比较原始,这里就省略了。  
  2. //        for (int i = 0; i < image.size(); i++)  
  3. //        {  
  4. //            File data=image.get(i);  
  5. //            String fileName=imageFileName.get(i);  
  6. //            fileName=path+"\\"+fileName;  
  7. //            data.renameTo(new File(fileName));  
  8. //        }  
  9.         return SUCCESS;  
  10.     }  
  11.   
  12.     public List<File> getImage()  
  13.     {  
  14.         return image;  
  15.     }  
  16.   
  17.     public void setImage(List<File> image)  
  18.     {  
  19.         this.image = image;  
  20.     }  
  21.   
  22.     public List<String> getImageContentType()  
  23.     {  
  24.         return imageContentType;  
  25.     }  
  26.   
  27.     public void setImageContentType(List<String> imageContentType)  
  28.     {  
  29.         this.imageContentType = imageContentType;  
  30.     }  
  31.   
  32.     public List<String> getImageFileName()  
  33.     {  
  34.         return imageFileName;  
  35.     }  
  36.   
  37.     public void setImageFileName(List<String> imageFileName)  
  38.     {  
  39.         this.imageFileName = imageFileName;  
  40.     }  
  41.      
  42. }  


第三步,编辑index.jsp用于上传,新建success.jsp用于上传成功后的提示,代码如下:

index.jsp:

[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>My JSP 'index.jsp' starting page</title>  
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   </head>  
  23.     
  24.   <body>  
  25.     <s:form action="upload" method="post" enctype="multipart/form-data" theme="simple">  
  26.         <s:file name="image" label="Data1"></s:file>  
  27.         <s:file name="image" label="Data2"></s:file>  
  28.         <s:submit></s:submit>  
  29.     </s:form>  
  30.   </body>  
  31. </html>  


success.jsp:

[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'success.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.         <h4>上传成功</h4>  
  27.         <p><a href="download.jsp">下载文件</a></p>  
  28.       
  29.   </body>  
  30. </html>  



第四步,新建struts.xml并配置web.xml,代码如下:(注:从struts.xml中可以看到,我这里对文件类型进行了规定,只能上传txt或者xml格式的文件)

struts.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.    <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.1.dtd">  
  5.       
  6.     <struts>  
  7.     <constant name="struts.multipart.saveDir" value="e:/"></constant>  
  8.         <package name="s2" extends="struts-default">  
  9.         <!-- 文件上传 -->  
  10.             <action name="upload" class="com.action.UploadAction">  
  11.                 <result>success.jsp</result>  
  12.                 <result name="input">index.jsp</result>  
  13.                 <interceptor-ref name="fileUpload">  
  14.                 <!-- 单个上传文件的最大值-->  
  15.                 <param name="maximumSize">409600</param>  
  16.                 <!-- 只能上传的文件的类型,可到tomcat的web-xml中查看各种文件类型-->  
  17.                 <param name="allowedTypes">text/plain , text/xml</param>  
  18.             </interceptor-ref>  
  19.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  20.             </action>  
  21.       
  22.               
  23.         </package>  
  24.     </struts>  

web.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  4.  <filter>  
  5.   <filter-name>s2</filter-name>  
  6.   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  7.  </filter>  
  8.  <filter-mapping>  
  9.   <filter-name>s2</filter-name>  
  10.   <url-pattern>/*</url-pattern>  
  11.  </filter-mapping>  
  12.  <welcome-file-list>  
  13.   <welcome-file>index.jsp</welcome-file>  
  14.  </welcome-file-list>  
  15.  <login-config>  
  16.   <auth-method>BASIC</auth-method>  
  17.  </login-config>  
  18. </web-app>  

第五步,部署项目并运行起来,键入http://localhost:8080/updownload/index.jsp,检验文件上传是否成功,成功的话会跳转到success,jsp提示成功,并在服务器的updownload的目录下自动创建images目录,并将上传的文件保存。假使不成功请根据报错检查项目并进行改正。


第六步,加入文件上传能功能,我们便接着在此基础上,完成文件的下载功能。

首先是新建com.action.DownloadAction.java,代码如下:

[java] view plaincopy
  1. package com.action;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.InputStream;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.net.URLEncoder;  
  8. import java.util.List;  
  9.   
  10. import org.apache.struts2.ServletActionContext;  
  11.   
  12. import com.opensymphony.xwork2.ActionSupport;  
  13. import com.sun.org.apache.regexp.internal.REUtil;  
  14.   
  15. public class DownloadAction extends ActionSupport  
  16. {  
  17.   
  18.     private static final long serialVersionUID = 1L;  
  19.       
  20.     private Dao dao=new Dao();  
  21.     private List<FileItem>list;  
  22.     private String fileId;      
  23.     private FileItem fileItem;  
  24.       
  25.     //获得list  
  26.     public String list()  
  27.     {  
  28.         list=dao.getFileList();  
  29.         return "list-success";  
  30.     }  
  31.     //获得文件  
  32.     public String get()  
  33.     {  
  34.         fileItem=dao.getFileItem(fileId);  
  35.         return "get-success";  
  36.     }  
  37.       
  38.     //获得输入流  
  39.     public InputStream getInputStream()  
  40.     {  
  41.         try  
  42.         {  
  43.             String path=ServletActionContext.getServletContext().getRealPath("/");  
  44.             String fileName=path+fileItem.getLocationPath();  
  45.             FileInputStream fis=new FileInputStream(fileName);  
  46.             return fis;  
  47.         }  
  48.         catch (FileNotFoundException e)  
  49.         {  
  50.             // TODO Auto-generated catch block  
  51.             e.printStackTrace();  
  52.         }  
  53.         return null;  
  54.     }  
  55.       
  56.     //获得文件类型  
  57.     public String getContentType()  
  58.     {  
  59.         return fileItem.getContentType();  
  60.     }  
  61.       
  62.     //获得文件下载位置  
  63.     public String getContentDisposition()  
  64.     {  
  65.         try  
  66.         {  
  67.             return "attachment;filename="+URLEncoder.encode(fileItem.getFileName(),"utf-8");  
  68.         }  
  69.         catch (UnsupportedEncodingException e)  
  70.         {  
  71.             // TODO Auto-generated catch block  
  72.             e.printStackTrace();  
  73.         }  
  74.         return null;  
  75.     }  
  76.       
  77.     //获得文件字节大小  
  78.     public int getContentLength()  
  79.     {  
  80.         return fileItem.getContentLength();  
  81.     }  
  82.       
  83.       
  84.     public List<FileItem> getList()  
  85.     {  
  86.         return list;  
  87.     }  
  88.   
  89.     public void setList(List<FileItem> list)  
  90.     {  
  91.         this.list = list;  
  92.     }  
  93.     public String getFileId()  
  94.     {  
  95.         return fileId;  
  96.     }  
  97.     public void setFileId(String fileId)  
  98.     {  
  99.         this.fileId = fileId;  
  100.     }  
  101.       
  102.   
  103. }  


第七步,新建一个com.action.FileItem.java的javabean,用来模拟数据库中对应的实体类,这里我们就模拟下。代码如下:

[java] view plaincopy
  1. package com.action;  
  2.   
  3.   
  4. public class FileItem  
  5. {  
  6.     private String fileId;  
  7.     private String fileName;  
  8.     private String contentType;  
  9.     private String locationPath;  
  10.     private int contentLength;  
  11.      
  12.       
  13.     //getter和setter略  
  14.       
  15. }  

第八步,写一个Dao,这个Dao原本该去查询数据库,并得到下载列表的,但是我们这里只是讲解struts2,所以便不连接数据库,如第七步一样,我们模拟出查询列表的方法,当然,查到的下载列表,就是我们在上传功能中,已经上传到服务器的文件列表。

所以我们新建的com.action.Dao的代码如下:

[java] view plaincopy
  1. package com.action;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8.   
  9. public class Dao  
  10. {  
  11.       
  12.     //静态数据,本该从数据库查出来的成为一个集合  
  13.     private static  Map<String, FileItem>files=new HashMap<String, FileItem>();  
  14.     static{  
  15.         long id=System.currentTimeMillis();  
  16.         String fileId="100"+id;  
  17.         files.put(fileId, new FileItem(fileId, "9-10.txt""text/plain""images\\9-10.txt"206));  
  18.         fileId="200"+id;  
  19.         files.put(fileId, new FileItem(fileId, "aaa.xml""text/xml""images\\aaa.xml"156));  
  20.         fileId="300"+id;  
  21.         files.put(fileId, new FileItem(fileId, "test.xml""application/xml""images\\test.xml"617));  
  22.         fileId="400"+id;  
  23.         files.put(fileId, new FileItem(fileId, "Tomcat支持的文件类型.txt""text/plain""images\\Tomcat支持的文件类型.txt"21*1024));  
  24.     }  
  25.       
  26.     //获得文件下载列表  
  27.     public List<FileItem> getFileList()  
  28.     {  
  29.         return new ArrayList<FileItem>(files.values());  
  30.     }  
  31.       
  32.       
  33.     //根据id获得单个文件  
  34.     public FileItem getFileItem(String fileName)  
  35.     {  
  36.         return files.get(fileName);  
  37.     }  
  38. }  

第九步:新建download.jsp和list-success.jsp,代码如下:

download.jsp:

[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'download.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.     <a href="download_list">显示下载列表</a>  
  27.   </body>  
  28.     
  29.   </html>br>  
  30.   </body>  
  31. </html>  

list-success.jsp:

[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>My JSP 'list-success.jsp' starting page</title>  
  14.       
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">      
  18.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.     <meta http-equiv="description" content="This is my page">  
  20.     <!-- 
  21.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  22.     -->  
  23.   
  24.   </head>  
  25.     
  26.   <body>   
  27.     <h4>文件下载列表</h4>  
  28.     <s:iterator value="list">  
  29.         <a href="download_get?fileId=${fileId} ">${fileName} </a>  
  30.         <br/><br/>  
  31.     </s:iterator>  
  32.   </body>  
  33. </html>  
[html] view plaincopy
  1.   
[html] view plaincopy
  1. 第十步:修改struts.xml并在文件上传的下面,配置文件下载的action,并在src目录下,添加i18n.properties资源文件,对项目中的可能错误进行国际化,并在struts.xml中进行引用,即:<constant name="struts.custom.i18n.resources" value="i18n"></constant><pre name="code" class="html"></pre>  
  2. <pre></pre>  
  3. <p></p>  
  4. <pre></pre>  
  5. <pre name="code" class="html">修改后的struts.xml如下:</pre><pre name="code" class="html"></pre><pre name="code" class="html"><pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>  
  6.    <!DOCTYPE struts PUBLIC  
  7.     "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"  
  8.     "http://struts.apache.org/dtds/struts-2.1.dtd">  
  9.       
  10.     <struts>  
  11.     <constant name="struts.multipart.saveDir" value="e:/"></constant>  
  12.     <constant name="struts.custom.i18n.resources" value="i18n"></constant>  
  13.         <package name="s2" extends="struts-default">  
  14.         <!-- 文件上传 -->  
  15.             <action name="upload" class="com.action.UploadAction">  
  16.                 <result>success.jsp</result>  
  17.                 <result name="input">index.jsp</result>  
  18.                 <interceptor-ref name="fileUpload">  
  19.                 <!-- 单个上传文件的最大值-->  
  20.                 <param name="maximumSize">409600</param>  
  21.                 <!-- 只能上传的文件的类型,可到tomcat的web-xml中查看各种文件类型-->  
  22.                 <param name="allowedTypes">text/plain , text/xml</param>  
  23.             </interceptor-ref>  
  24.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  25.             </action>  
  26.           
  27.         <!-- 文件下载 -->  
  28.             <action name="download_*" class="com.action.DownloadAction" method="{1}">  
  29.                 <result name="{1}-success">{1}-success.jsp</result>  
  30.                 <result name="get-success" type="stream"></result>  
  31.             </action>  
  32.               
  33.         </package>  
  34.     </struts></pre><pre name="code" class="html"></pre>i18n.properties文件,代码如下:<pre name="code" class="html">struts.messages.error.uploading=\u6587\u4EF6\u4E0A\u4F20\u9519\u8BEF  
  35. struts.messages.error.file.too.large=\u6587\u4EF6\u8FC7\u5927  
  36. struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u7C7B\u578B\u4E0D\u5141\u8BB8  
  37. struts.messages.error.file.extension.not.allowed=\u6587\u4EF6\u6269\u5C55\u540D\u4E0D\u5141\u8BB8</pre><pre name="code" class="html"></pre><pre name="code" class="html"></pre><pre name="code" class="html"></pre><pre name="code" class="html"></pre><pre name="code" class="html"></pre><pre name="code" class="html"></pre><pre name="code" class="html"></pre><pre name="code" class="html"></pre><pre name="code" class="html"><pre name="code" class="html">【csdn】的附件上传真实太坑了,还得先上传为资源,再提供下载链接,我这边儿都上传了,可是还是看不见链接,没办法,只能给出我的iteye链接,<a href="http://jackjobs.iteye.com/blog/1699240">http://jackjobs.iteye.com/blog/1699240</a>,它是直接能下载的,也不要积分什么的,为此,还得鄙视一下csdn这种附件下载积分的做法,(#‵′)凸</pre>  
  38. <pre></pre>  
  39. <pre></pre>  
  40. <pre></pre>  
  41. <pre></pre>  
  42. <pre></pre>  
  43. <pre></pre>  
  44. <pre></pre>  
  45. <pre></pre>  
  46. <pre></pre>  
  47. <pre></pre>  
  48. <pre></pre>  
  49. <pre></pre>  
  50. <pre></pre>  
  51. <pre></pre>  
  52.      
  53. </pre></pre>  

0 0
原创粉丝点击