Struts2(多)文件上传和下载使用示例

  1. 云栖社区>
  2. 博客>
  3. 正文

Struts2(多)文件上传和下载使用示例

聚优云惠 2013-11-05 10:44:37 浏览392
展开阅读全文

  1. /** 
  2.  * Struts2Test 
  3.  * 使用Struts2上传文件 
  4.  */  
  5. package com.labci.struts2.action;  
  6. import java.io.File;  
  7. import java.io.FileInputStream;  
  8. import java.io.FileOutputStream;  
  9. import java.util.ArrayList;  
  10. import java.util.Arrays;  
  11. import java.util.List;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import org.apache.struts2.interceptor.ServletRequestAware;  
  14. import com.opensymphony.xwork2.ActionSupport;  
  15. /** 
  16.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  17.  * Jun 8, 2011[8:31:01 PM] 
  18.  * 
  19.  */  
  20. public class UploadFileAction extends ActionSupport implements  
  21.         ServletRequestAware {  
  22.     /** 
  23.      *  
  24.      */  
  25.     private static final long serialVersionUID = -1896915260152387341L;  
  26.     private HttpServletRequest request;  
  27.     public void setServletRequest(HttpServletRequest req) {  
  28.         this.request=req;  
  29.     }  
  30.       
  31.       
  32.     private List<File> fileName;//这里的"fileName"一定要与表单中的文件域名相同  
  33.     private List<String> fileNameContentType;//格式同上"fileName"+ContentType  
  34.     private List<String> fileNameFileName;//格式同上"fileName"+FileName  
  35.     private String savePath;//文件上传后保存的路径  
  36.     private String allowTypes;//允许上传的文件类型  
  37.       
  38.     public List<File> getFileName() {  
  39.         return fileName;  
  40.     }  
  41.   
  42.     public void setFileName(List<File> fileName) {  
  43.         this.fileName = fileName;  
  44.     }  
  45.   
  46.     public List<String> getFileNameContentType() {  
  47.         return fileNameContentType;  
  48.     }  
  49.   
  50.     public void setFileNameContentType(List<String> fileNameContentType) {  
  51.         this.fileNameContentType = fileNameContentType;  
  52.     }  
  53.   
  54.     public List<String> getFileNameFileName() {  
  55.         return fileNameFileName;  
  56.     }  
  57.   
  58.     public void setFileNameFileName(List<String> fileNameFileName) {  
  59.         this.fileNameFileName = fileNameFileName;  
  60.     }  
  61.   
  62.     @SuppressWarnings("deprecation")  
  63.     public String getSavePath() {  
  64.         return request.getRealPath(savePath);  
  65.     }  
  66.   
  67.     public void setSavePath(String savePath) {  
  68.         this.savePath = savePath;  
  69.     }  
  70.     public String getAllowTypes() {  
  71.         return allowTypes;  
  72.     }  
  73.   
  74.     public void setAllowTypes(String allowTypes) {  
  75.         this.allowTypes = allowTypes;  
  76.     }  
  77.       
  78.     @Override  
  79.     public String execute() throws Exception {  
  80.         //得到文件的类型  
  81.         List<String> fileTypes=getFileNameContentType();  
  82.         String []allowTypes=getAllowTypes().split(",");  
  83.         List<String> typesList=Arrays.asList(allowTypes);  
  84.           
  85.         boolean allowFlag=true;//是否存在不允许上传的文件类型  
  86.         for(String type:fileTypes){  
  87.             if(!typesList.contains(type)){  
  88.                 allowFlag=false;  
  89.                 break;  
  90.             }  
  91.         }  
  92.         if(!allowFlag){  
  93.             request.setAttribute("fileTypeError",   
  94.                     "您上传的文件中存在不允许上传的类型,允许上传的类型为:"+getAllowTypes());  
  95.             return INPUT;  
  96.         }  
  97.           
  98.         //允许上传  
  99.         File dir=new File(getSavePath());  
  100.         if(!dir.exists()){  
  101.             dir.mkdirs();  
  102.         }  
  103.         List<File> files=getFileName();  
  104.         for(int i=0;i<files.size();i++){  
  105.             FileOutputStream fos=new FileOutputStream(getSavePath()+"//"+getFileNameFileName().get(i));  
  106.             FileInputStream fis=new FileInputStream(getFileName().get(i));  
  107.             byte []buffers=new byte[1024];  
  108.             int len=0;  
  109.             while((len=fis.read(buffers))!=-1){  
  110.                 fos.write(buffers,0,len);  
  111.             }  
  112.         }  
  113.           
  114.         List<String> fileHrefsList=new ArrayList<String>();  
  115.         for(String fileName:getFileNameFileName()){  
  116.             String href="<a href="/" mce_href="/""downloadFile.action?fileName="+fileName+"/">"+fileName+"</a>";  
  117.             fileHrefsList.add(href);  
  118.         }  
  119.         request.setAttribute("fileNameList", fileHrefsList);  
  120.         return SUCCESS;  
  121.     }  
  122.   
  123. }  
 

  1. <%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>Struts2多文件上传</title>  
  7.   </head>  
  8.     
  9.   <body>  
  10.     <table>  
  11.         <tr>  
  12.             <td>  
  13.                 <c:choose>  
  14.                     <c:when test="${!empty fileTypeError}">  
  15.                         <font color="red"><b>${fileTypeError}</b></font>  
  16.                     </c:when>  
  17.                     <c:otherwise>  
  18.                         <c:forEach items="${fileNameList}" var="fileName">  
  19.                             ${fileName}<br/>  
  20.                         </c:forEach>  
  21.                     </c:otherwise>  
  22.                 </c:choose>  
  23.             </td>  
  24.         </tr>       
  25.     </table>  
  26.     <!-- 不一定要选择所有文件才可以上传 -->  
  27.     <form action="uploadFile.action" method="post" enctype="multipart/form-data">  
  28.         <input type="file" name="fileName"/><br/>  
  29.         <input type="file" name="fileName"/><br/>  
  30.         <input type="file" name="fileName"/><br/>  
  31.         <input type="submit" value="上传"/>  
  32.     </form>  
  33.   </body>  
  34. </html>  
 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  5.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  6.     <filter>  
  7.         <filter-name>struts2</filter-name>  
  8.         <filter-class>  
  9.             org.apache.struts2.dispatcher.FilterDispatcher  
  10.         </filter-class>  
  11.     </filter>  
  12.     <filter-mapping>  
  13.         <filter-name>struts2</filter-name>  
  14.         <url-pattern>*.action</url-pattern>  
  15.     </filter-mapping>  
  16.     <welcome-file-list>  
  17.         <welcome-file>index.jsp</welcome-file>  
  18.     </welcome-file-list>  
  19. </web-app>  
 

  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. <struts>  
  6.     <constant name="struts.devMode" value="false" />  
  7.     <!-- 改变struts2默认为2M的上传文件大小限制 -->  
  8.     <constant name="struts.multipart.maxSize" value="10240000"/>  
  9.     <package name="upload" extends="struts-default">  
  10.         <action name="uploadFile" class="com.labci.struts2.action.UploadFileAction">  
  11.             <param name="savePath">/upload</param>  
  12.             <param name="allowTypes">text/plain,text/xml,text/html,image/gif,image/png,image/jpeg,image/jpg,image/bmp</param>  
  13.             <result name="success">index.jsp</result>  
  14.             <result name="input">index.jsp</result>  
  15.         </action>  
  16.         <action name="downloadFile" class="com.labci.struts2.action.DownloadFileAction">  
  17.             <param name="savePath">/upload</param>  
  18.             <result name="success">index.jsp</result>  
  19.         </action>  
  20.     </package>  
  21. </struts>  
 

  1. /** 
  2.  * Struts2Test 
  3.  * 文件下载的Action 
  4.  */  
  5. package com.labci.struts2.action;  
  6. import java.io.FileInputStream;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import org.apache.struts2.interceptor.ServletRequestAware;  
  12. import org.apache.struts2.interceptor.ServletResponseAware;  
  13. import com.opensymphony.xwork2.ActionSupport;  
  14. /** 
  15.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  16.  * Jun 8, 2011[9:15:15 PM] 
  17.  * 
  18.  */  
  19. public class DownloadFileAction extends ActionSupport implements  
  20.         ServletRequestAware, ServletResponseAware {  
  21.       
  22.     /** 
  23.      *  
  24.      */  
  25.     private static final long serialVersionUID = -7448748577778248376L;  
  26.     private HttpServletRequest request;  
  27.     private HttpServletResponse response;  
  28.     private String savePath;  
  29.       
  30.     @Override  
  31.     public String execute() throws Exception {  
  32.           
  33.         String fileName=request.getParameter("fileName");  
  34.         String fullPath=getSavePath()+"//"+fileName;  
  35.         fileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");  
  36.         InputStream is=new FileInputStream(fullPath);  
  37.         int len=0;  
  38.         byte []buffers=new byte[1024];  
  39.         response.reset();  
  40.         response.setContentType("application/x-msdownload");  
  41.         response.addHeader("Content-Disposition""attachment;filename=/""+fileName+"/"");  
  42.           
  43.         //把文件内容通过输出流打印到页面上供下载  
  44.         while((len=is.read(buffers))!=-1){  
  45.             OutputStream os=response.getOutputStream();  
  46.             os.write(buffers, 0, len);  
  47.         }  
  48.           
  49.         is.close();  
  50.           
  51.         return SUCCESS;  
  52.     }  
  53.     public void setServletRequest(HttpServletRequest req) {  
  54.         this.request=req;  
  55.     }  
  56.     public void setServletResponse(HttpServletResponse resp) {  
  57.         this.response=resp;  
  58.     }  
  59.     @SuppressWarnings("deprecation")  
  60.     public String getSavePath() {  
  61.         return request.getRealPath(savePath);  
  62.     }  
  63.     public void setSavePath(String savePath) {  
  64.         this.savePath = savePath;  
  65.     }  
  66.       
  67. }  
 

 

 

 

 

 

 

 

 

网友评论

登录后评论
0/500
评论
聚优云惠
+ 关注