一、文件上传

二、文件下载

三、传输文件大小问题

引用jar包为:
xwork-2.1.2.jar
struts2-core-2.1.6.jar
ognl-2.6.11.jar
jstl-1.2.jar
freemarker-2.3.13.jar
commons-logging-1.0.4.jar
commons-io-1.3.2.jar
commons-fileupload-1.2.1.jar

一、文件上传

上传我们从上传页面开始讲起,下面为上传页面upload.jsp。

其中,我们需要注意的是form标签中的enctype="multipart/form-data",没有这个不能上传文件。

 
  
  1. <%@ page language="java" contentType="text/html; charset=utf-8"%> 
  2. <%@ taglib prefix="s" uri="/struts-tags"%> 
  3. <html> 
  4.     <head> 
  5.         <title>upload</title> 
  6.  
  7.     </head> 
  8.  
  9.     <body> 
  10.  
  11.         <script type="text/javascript"> 
  12.  
  13. <!--addMore函数可以提供上传多个文件上传--> 
  14.  
  15. function addMore()  
  16. {  
  17.  
  18.     var td = document.getElementById("more");  
  19.       
  20.     var br = document.createElement("br");  
  21.     var input = document.createElement("input");  
  22.     var button = document.createElement("input");  
  23.       
  24.     input.type = "file";  
  25.     input.name = "upload";  
  26.       
  27.     button.type = "button";  
  28.     button.value = "   删除    ";  
  29.       
  30.     button.onclick = function()  
  31.     {  
  32.         td.removeChild(br);  
  33.         td.removeChild(input);  
  34.         td.removeChild(button);  
  35.     }  
  36.       
  37.     td.appendChild(br);  
  38.     td.appendChild(input);  
  39.     td.appendChild(button);  
  40. }  
  41.  
  42. </script> 
  43.  
  44.         <!--<h3><font color="red">上传文件类型后缀为doc,ppt,xls,pdf,txt,java,每个文件大小不能大于50M</font></h3>--> 
  45.  
  46.         <table align="center" width="50%"> 
  47.             <tr> 
  48.                 <td> 
  49.  
  50.                                         <s:fielderror cssStyle="color:red" /> 
  51.  
  52.                 </td> 
  53.             </tr> 
  54.         </table> 
  55.           
  56.         <s:form action="upload.action" theme="simple" method="post" 
  57.             enctype="multipart/form-data"> 
  58.  
  59.             <table align="center" width="50%" border="1"> 
  60.                 <tr> 
  61.                     <td> 
  62.                         上传文件  
  63.                     </td> 
  64.                     <td id="more" > 
  65.                         <s:file name="upload"></s:file> 
  66.                         <input type="button" value="上传更多..." onclick="addMore()"> 
  67.                     </td> 
  68.                 </tr> 
  69.                 <tr> 
  70.                     <td> 
  71.                         <s:submit value=" 确认 "></s:submit> 
  72.                     </td> 
  73.                     <td> 
  74.                         <s:reset value=" 重置 "></s:reset> 
  75.                     </td> 
  76.                 </tr> 
  77.  
  78.             </table> 
  79.  
  80.         </s:form> 
  81.  
  82.     </body> 
  83.  
  84.  
  85. </html> 

然后是struts.xml:

 
  
  1. <action name="upload" class="org.usc.file.UploadAction"> 
  2.             <result name="input">/upload.jsp</result>  
  3.             <result name="success">/upload_success.jsp</result> 
  4.        </action> 

跳转到UploadAction

文件上传路径为WebContent下的upload,所以最好先建立好此根目录

 
  
  1. package org.usc.file;  
  2.  
  3. import java.io.File;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.UUID;  
  7. import org.apache.commons.io.FileUtils;  
  8. import org.apache.struts2.ServletActionContext;  
  9. import org.usc.utils.UploadConfigurationRead;  
  10. import com.opensymphony.xwork2.ActionSupport;  
  11.  
  12. /**  
  13.  * 多文件上传类  
  14.  */ 
  15. public class UploadAction extends ActionSupport  
  16. {  
  17.  
  18.     /**  
  19.      *   
  20.      */ 
  21.     private static final long serialVersionUID = 1L;  
  22.     private File[] upload;// 实际上传文件  
  23.     private String[] uploadContentType; // 文件的内容类型  
  24.     private String[] uploadFileName; // 上传文件名  
  25.         public String execute() throws Exception  
  26.     {  
  27.         try 
  28.         {  
  29.             //文件上传存放路径  
  30.             String targetDirectory = ServletActionContext.getServletContext()  
  31.                     .getRealPath("/"+ UploadConfigurationRead.getInstance().getConfigItem("uploadFilePath").trim());// 获得路径  
  32.             for (int i = 0; i < upload.length; i++)  
  33.             {  
  34.                 String fileName = uploadFileName[i];// 上传的文件名  
  35.                 String type = uploadContentType[i];// 文件类型  
  36.                 System.out.println("====filename:"+fileName);  
  37.                 String realName = UUID.randomUUID().toString()+ getExt(fileName);// 保存的文件名称,使用UUID+后缀进行保存  
  38.                 System.out.println("====getExt(fileName):"+getExt(fileName));  
  39.                 System.out.println("====realName:"+realName);  
  40.                   
  41.                 File target = new File(targetDirectory, realName);  
  42.                 FileUtils.copyFile(upload[i], target);// 上传至服务器的目录,一般都这样操作,  
  43.                                                         // 在把路径写入数据库即可  
  44.                 System.out.println("====targetDirectory:"+targetDirectory);  
  45.  
  46.              }  
  47.              
  48.         } catch (Exception e)  
  49.         {  
  50.             e.printStackTrace();  
  51.             addActionError(e.getMessage());  
  52.  
  53.             return INPUT;  
  54.         }  
  55.  
  56.         return SUCCESS;  
  57.  
  58.     }  
  59.  
  60.     public File[] getUpload()  
  61.     {  
  62.         return upload;  
  63.     }  
  64.  
  65.     public void setUpload(File[] upload)  
  66.     {  
  67.         this.upload = upload;  
  68.     }  
  69.  
  70.     public String[] getUploadContentType()  
  71.     {  
  72.         return uploadContentType;  
  73.     }  
  74.  
  75.     public void setUploadContentType(String[] uploadContentType)  
  76.     {  
  77.         this.uploadContentType = uploadContentType;  
  78.     }  
  79.  
  80.     public String[] getUploadFileName()  
  81.     {  
  82.         return uploadFileName;  
  83.     }  
  84.  
  85.     public void setUploadFileName(String[] uploadFileName)  
  86.     {  
  87.         this.uploadFileName = uploadFileName;  
  88.     }  
  89.  
  90.     public static String getExt(String fileName)  
  91.     {  
  92.         return fileName.substring(fileName.lastIndexOf("."));  
  93.     }  
  94.  
  95. }  

二、文件下载

 struts.xml:

 
  
  1. <!-- 下载文件 --> 
  2. <action name="download" class="com.DownloadAction"> 
  3.          <result name="success" type="stream"> 
  4.             <param name="contentDisposition">p_w_upload;filename="${fileName}"</param> 
  5.             <param name="inputName">downloadFile</param> 
  6.          </result> 
  7.       </action> 
  8.  
  9. <!-- 进入文件下载列表 --> 
  10. <action name="inputdownload" class="com.DownloadAction" method="list"> 
  11.          <result name="success">/download.jsp</result> 
  12.       </action> 

下载文件实体类

 
  
  1. package com;  
  2.  
  3. /**  
  4.  * 文件类,需要的时候,可以和数据库进行关联  
  5.  */ 
  6. public class DownloadFiles  
  7. {  
  8.     private String downloadFileName;//上传的文件名称  
  9.     private String downloadContentType;//类型  
  10.     private String downloadRealName;//保存的文件真实名称,UUID  
  11.     //如果使用数据库的话,建议这三个字段都进行保存  
  12.       
  13.     public String getDownloadFileName() {  
  14.         return downloadFileName;  
  15.     }  
  16.     public void setDownloadFileName(String downloadFileName) {  
  17.         this.downloadFileName = downloadFileName;  
  18.     }  
  19.     public String getDownloadContentType() {  
  20.         return downloadContentType;  
  21.     }  
  22.     public void setDownloadContentType(String downloadContentType) {  
  23.         this.downloadContentType = downloadContentType;  
  24.     }  
  25.     public String getDownloadRealName() {  
  26.         return downloadRealName;  
  27.     }  
  28.     public void setDownloadRealName(String downloadRealName) {  
  29.         this.downloadRealName = downloadRealName;  
  30.     }  
  31.       
  32. }  

文件下载的Action

 
  
  1. package com;  
  2.  
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.UnsupportedEncodingException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.  
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.  
  11. import org.apache.struts2.ServletActionContext;  
  12. import com.UploadConfigurationRead;  
  13.  
  14. public class DownloadAction extends ActionSupport  
  15. {  
  16.     private static final long serialVersionUID = 6329383258366253255L;  
  17.     private String fileName;  
  18.     private String fileRealName;  
  19.     private List<DownloadFiles> downloadFiles;  
  20.     //上传文件存放路径  
  21.     private final static String UPLOADDIR = "/upload";  
  22.       
  23.     public List<DownloadFiles> getDownloadFiles() {  
  24.         return downloadFiles;  
  25.     }  
  26.  
  27.     public void setDownloadFiles(List<DownloadFiles> downloadFiles) {  
  28.         this.downloadFiles = downloadFiles;  
  29.     }  
  30.  
  31.     public void setFileName()  
  32.     {  
  33.         // 得到请求下载的文件名  
  34.         String fname = ServletActionContext.getRequest().getParameter("name");  
  35.         String frealname = ServletActionContext.getRequest().getParameter("realname");  
  36.         try 
  37.         {  
  38.             /*  
  39.              * 对fname参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK。  
  40.              * 这里使用request.setCharacterEncoding解码无效.  
  41.              * 只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件  
  42.              */ 
  43.             if(null != fname && null != frealname){  
  44.                 fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");  
  45.                 frealname= new String(frealname.getBytes("ISO-8859-1"), "UTF-8");  
  46.             }else{  
  47.                 fname = new String("null!");  
  48.                 frealname= new String("null!");  
  49.             }  
  50.         } catch (Exception e)  
  51.         {  
  52.             e.printStackTrace();  
  53.         }  
  54.         this.fileName = fname;  
  55.         this.fileRealName = frealname;   
  56.     }  
  57.  
  58.     /*  
  59.      * @getFileName 此方法对应的是struts.xml文件中的: <param  
  60.      * name="contentDisposition">p_w_upload;filename="${fileName}"</param>  
  61.      * 这个属性设置的是下载工具下载文件时显示的文件名, 要想正确的显示中文文件名,我们需要对fileName再次编码  
  62.      * 否则中文名文件将出现乱码,或无法下载的情况  
  63.      */ 
  64.     public String getFileName() throws UnsupportedEncodingException  
  65.     {  
  66.  
  67.         fileRealName = new String(fileRealName.getBytes(), "ISO-8859-1");  
  68.  
  69.         return fileRealName;  
  70.     }  
  71.  
  72.     /*  
  73.      * @getDownloadFile 此方法对应的是struts.xml文件中的: <param  
  74.      * name="inputName">downloadFile</param> 返回下载文件的流,可以参看struts2的源码  
  75.      */ 
  76.     public InputStream getDownloadFile()  
  77.     {  
  78.  
  79.         this.setFileName();  
  80.         return ServletActionContext.getServletContext().getResourceAsStream("/"+UploadConfigurationRead.getInstance().getConfigItem("uploadFilePath").trim()+"/" + fileName);  
  81.     }  
  82.  
  83.     @Override 
  84.     public String execute() throws Exception  
  85.     {  
  86.         return SUCCESS;  
  87.     }  
  88.       
  89.     public String list() throws Exception {  
  90.         //工程目录下的UPLOADDIR目录  
  91.         String dir = ServletActionContext.getServletContext().getRealPath(UPLOADDIR);  
  92.         System.out.println("====dir:"+dir);  
  93.         File file = new java.io.File(dir);  
  94.         File[] files = file.listFiles();  
  95.         System.out.println("====filenames:"+files.length);  
  96.         this.downloadFiles = new ArrayList<DownloadFiles>();  
  97.         for(int i=0;i<files.length;i++){  
  98.             DownloadFiles downloadFile = new DownloadFiles();  
  99.             downloadFile.setDownloadFileName(files[i].getName());  
  100.             downloadFile.setDownloadRealName(files[i].getAbsolutePath());  
  101.             downloadFile.setDownloadContentType("1");  
  102.             System.out.println("====Name:"+files[i].getName());  
  103.             System.out.println("====Absolutepath:"+files[i].getAbsolutePath());  
  104.             this.downloadFiles.add(downloadFile);  
  105.         }  
  106.         return SUCCESS;  
  107.     }  

文件下载页面download.jsp

 

 
  
  1. <%@ page language="java" contentType="text/html; charset=utf-8"%> 
  2. <%@ taglib prefix="s" uri="/struts-tags"%> 
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
  4. <html> 
  5.     <head> 
  6.         <title>download</title> 
  7.     </head> 
  8.     <body> 
  9. <!-- 下面展示了两种显示下载文件列表的方式-->
  10.         <%--    <s:iterator value="uploadFileName" id="downloadFileName">--%> 
  11.         <%--                <a href="download.action?name=<s:property value='%{#downloadFileName}'/>"><s:property value="%{#%{#downloadFileName}}" /> </a>--%> 
  12.         <%--                <br>--%> 
  13.         <%--    </s:iterator>--%> 
  14.         <table align="center" width="50%" border="1"> 
  15.             <tr> 
  16.                 <td align="center"> 
  17.                     文件下载  
  18.                 </td> 
  19.             </tr> 
  20.             <c:forEach var="downloadFiles" items="${downloadFiles}"> 
  21.                 <tr> 
  22.                     <td> 
  23. <!-- 因为我没有使用UUID来存储文件,所以此处 下载文件名与实际名相同--> 
  24.                         <a 
  25.                             href="download.action?name=${downloadFiles.downloadFileName }&realname=${downloadFiles.downloadFileName }">${downloadFiles.downloadFileName  
  26.                             }</a> 
  27.                     </td> 
  28.                 </tr> 
  29.  
  30.             </c:forEach> 
  31.               
  32.             <s:debug/> 
  33.  
  34.  
  35.         </table> 
  36.     </body> 
  37. </html> 

三、传输文件大小问题

        本文讲述的是在struts2框架下的文件上传与下载,struts2默认的文件最大值大约是2M,如果超过2M,文件将不上传,而添加拦截器的方式本人试过后也没有起效果。

以下是看到人家的一种解决方式:http://hi.baidu.com/%CE%D2%B0%AE%E1%B0%CF%D8/blog/item/92db3726f01f9926d4074287.html