分享

struts2文件上传

 dawn001 2014-09-27

对于struts2文件上传之前写过一个,是通过struts.properties的配置实现的,现在将配置信息改到了struts.xml中,一样可以成功了。

实现对文件上传类型,文件大小上限,保存文件绝路路径参数注入action。



上传jsp页面:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags"%>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>发微博</title>  
  7.     <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  8.       
  9.   </head>  
  10.     
  11.   <body style="font-size:14px;">  
  12.     <h2>写微博      <a href="index.jsp">返回首页</a></h2>  
  13.     <form action="upload" method="post" enctype="multipart/form-data">  
  14.         <textarea name="sayMessage" rows="4" cols="50"></textarea><br>  
  15.         发文件<input name="upload" type="file"/><input type="submit" value="发微博">  
  16.     </form>  
  17.     <s:fielderror></s:fielderror>  
  18.   </body>  
  19. </html>  



struts2.xml文件中顶部常量配置部分:

  1. <!-- 配置文件上传时临时文件存放路径,我测试的过程中没配,报错说该项为空。 -->  
  2.     <constant name="struts.multipart.saveDir" value="E:\UploadFileDemo\tmp"></constant>  
  3.     <!-- 设置上传大小上限:200M -->  
  4.     <constant name="struts.multipart.maxSize" value="209715200"></constant>  
  5.     <!-- 指定资源文件 -->  
  6.     <constant name="struts.custom.i18n.resources" value="ApplicationResource"></constant>  

struts2.xml文件中action部分:

  1. <action name="upload" class="myFileUploadAction">  
  2.             <result name="success">/index.jsp</result>  
  3.             <result name="input">/saymessage.jsp</result>  
  4.             <!--struts2默认只能上传2M文件,类型不限。 配置拦截器来限制上传文件的类型和大小 -->  
  5.             <interceptor-ref name="fileUpload">  
  6.                 <!-- 限定文件上传类型 -->  
  7.                 <param name="allowedTypes">image/png,image/x-png,image/jpg,image/pjpeg,image/bmp,image/gif</param>  
  8.                 <!-- maximumSize指每个上传文件的大小上限,单位为:byte,这里设为30M,该值不能大于struts.multipart.maxSize总大小 -->  
  9.                 <param name="maximumSize">31457280</param>                
  10.             </interceptor-ref>              
  11.             <!-- 默认拦截器栈 -->  
  12.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  13.             <!-- 注入文件上传路径参数到myFileUploadAction中 -->  
  14.             <param name="savePath">E:\\UploadFileDemo</param>  
  15.               
  16.         </action>  


文件上传action代码:

  1. package com.gifer.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.sql.Timestamp;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Calendar;  
  8. import java.util.Date;  
  9. import java.util.HashSet;  
  10. import java.util.List;  
  11. import java.util.Random;  
  12. import java.util.Set;  
  13.   
  14. import org.apache.commons.io.FileUtils;  
  15. import org.apache.log4j.Logger;  
  16.   
  17. import com.gifer.model.LoginUser;  
  18. import com.gifer.model.SayFiles;  
  19. import com.gifer.model.SayMessage;  
  20. import com.gifer.service.SayMessageService;  
  21. import com.opensymphony.xwork2.ActionContext;  
  22. import com.opensymphony.xwork2.ActionSupport;  
  23.   
  24. public class FileUpLoadAction extends ActionSupport {  
  25.   
  26.     private static final long serialVersionUID = -1232100382633301276L;  
  27.   
  28.     private static final Logger log = Logger.getLogger(FileUpLoadAction.class);  
  29.   
  30.     // 微博内容  
  31.     private String sayMessage;  
  32.   
  33.     // 上传多个文件的集合文本  
  34.     private List<File> upload;  
  35.   
  36.     // 多个上传文件的类型集合  
  37.     private List<String> uploadContextType;  
  38.   
  39.     // 多个上传文件的文件名集合  
  40.     private List<String> uploadFileName;  
  41.   
  42.     // 文件存放路径根目录  
  43.     private String savePath;  
  44.   
  45.     private SayMessageService sayMessageService;  
  46.   
  47.     public String getSayMessage() {  
  48.         return sayMessage;  
  49.     }  
  50.   
  51.     public void setSayMessage(String sayMessage) {  
  52.         this.sayMessage = sayMessage;  
  53.     }  
  54.   
  55.     public List<File> getUpload() {  
  56.         return upload;  
  57.     }  
  58.   
  59.     public void setUpload(List<File> upload) {  
  60.         this.upload = upload;  
  61.     }  
  62.   
  63.     public List<String> getUploadContextType() {  
  64.         return uploadContextType;  
  65.     }  
  66.   
  67.     public void setUploadContextType(List<String> uploadContextType) {  
  68.         this.uploadContextType = uploadContextType;  
  69.     }  
  70.   
  71.     public List<String> getUploadFileName() {  
  72.         return uploadFileName;  
  73.     }  
  74.   
  75.     public void setUploadFileName(List<String> uploadFileName) {  
  76.         this.uploadFileName = uploadFileName;  
  77.     }  
  78.   
  79.     /** 
  80.      * 从配置文件注入文件根目录参数,绝对路径 
  81.      *  
  82.      * @param savePath 
  83.      */  
  84.     public void setSavePath(String savePath) {  
  85.         this.savePath = savePath;  
  86.     }  
  87.   
  88.     public void setSayMessageService(SayMessageService sayMessageService) {  
  89.         this.sayMessageService = sayMessageService;  
  90.     }  
  91.   
  92.     @Override  
  93.     public String execute() throws Exception {  
  94.   
  95.         try {  
  96.             // 把上传的文件放到指定的路径下 取相对路径  
  97.             // savePath = ServletActionContext.getServletContext().getRealPath(  
  98.             // "/WEB-INF/uploadfiles");  
  99.   
  100.             Calendar myDate = Calendar.getInstance();  
  101.             int intYear = myDate.get(Calendar.YEAR);  
  102.             int intMonth = myDate.get(Calendar.MONTH) + 1;  
  103.             int intDate = myDate.get(Calendar.DATE);  
  104.   
  105.             // 一律使用'/'以兼容windows和linux操作系统路径  
  106.             // 文件url相对路径  
  107.             String relativeUrl = "Files/" + intYear + "/" + intMonth + "/"  
  108.                     + intDate + "/";  
  109.             // 文件保存绝对路径  
  110.             savePath += "/" + intYear + "/" + intMonth + "/" + intDate;  
  111.   
  112.             // 文件保存目录  
  113.             File files = new File(savePath);  
  114.             // 如果指定的路径没有就创建  
  115.             if (!files.exists()) {  
  116.                 files.mkdirs();  
  117.             }  
  118.   
  119.             // 组织成微博实体对象  
  120.             SayMessage sayMessage = new SayMessage();  
  121.             sayMessage.setSayContent(this.getSayMessage());  
  122.             Timestamp sayTime = new Timestamp(System.currentTimeMillis());  
  123.             sayMessage.setSayTime(sayTime);// 当前时间  
  124.             LoginUser sayUser = (LoginUser) ActionContext.getContext()  
  125.                     .getSession().get("user");// 从session中获取用户信息  
  126.             sayMessage.setSayUser(sayUser.getUserId());  
  127.   
  128.             Set sayFiles = new HashSet();  
  129.   
  130.             // 把得到的文件的集合通过循环的方式读取并放在指定的路径下  
  131.             for (int i = 0; i < upload.size(); i++) {  
  132.                 try {  
  133.                     SayFiles sayFile = new SayFiles();  
  134.   
  135.                     String oldFileName = uploadFileName.get(i);// 上传文件原名  
  136.   
  137.                     // 生成随机文件名:当前年月日时分秒+五位随机数(为了在实际项目中防止文件同名而进行的处理)  
  138.                     Random r = new Random();  
  139.                     int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000// 获取随机数  
  140.                     SimpleDateFormat sDateFormat = new SimpleDateFormat(  
  141.                             "yyyyMMddHHmmss"); // 时间格式  
  142.                     String nowTimeStr = sDateFormat.format(new Date()); // 当前时间字符串  
  143.                     String extName = "";  
  144.                     // 获取拓展名  
  145.                     if (oldFileName.lastIndexOf(".") >= 0) {  
  146.                         extName = oldFileName.substring(oldFileName  
  147.                                 .lastIndexOf("."));  
  148.                     }  
  149.                     // 新文件名  
  150.                     String newFileName = nowTimeStr + rannum + extName;  
  151.                     relativeUrl += newFileName;// 文件保存到数据库中的相对路径  
  152.                     // list集合通过get(i)的方式来获取索引  
  153.                     // 将文件逐一复制到指定目录  
  154.                     FileUtils.copyFile(upload.get(i), new File(files,  
  155.                             newFileName));  
  156.                     sayFile.setFileName(oldFileName);  
  157.                     sayFile.setFileUrl(relativeUrl);  
  158.                     sayFile.setUploadTime(sayTime);  
  159.                     sayFile.setSayMessage(sayMessage);  
  160.                     sayFiles.add(sayFile);  
  161.                 } catch (IOException e) {  
  162.                     log.error(e.getMessage(), e);  
  163.                 }  
  164.             }  
  165.             sayMessage.setSayFileses(sayFiles);  
  166.             this.sayMessageService.save(sayMessage);  
  167.   
  168.         } catch (Exception e) {  
  169.             log.error(e.getMessage(), e);  
  170.             throw new RuntimeException();  
  171.         }  
  172.   
  173.         return SUCCESS;  
  174.     }  
  175.   
  176. }  

ApplicationResource.properties资源文件
  1. #Generated by ResourceBundle Editor (http://eclipse-rbe.)  
  2.   
  3. login.user.password         = \u5BC6\u7801  
  4. login.user.password.invalid = \u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A  
  5. login.user.userId           = \u7528\u6237\u540D  
  6. login.user.userId.invalid   = \u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A  
  7. #\u66F4\u6539\u4E0A\u4F20\u6587\u4EF6\u7C7B\u578B\u4E0D\u5141\u8BB8\u7684\u63D0\u793A\u4FE1\u606F    
  8. struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6\u7C7B\u578B\u4E0D\u88AB\u5141\u8BB8  
  9. #\u66F4\u6539\u4E0A\u4F20\u6587\u4EF6\u592A\u5927\u7684\u63D0\u793A\u4FE1\u606F    
  10. struts.messages.error.file.too.large=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u4E0A\u9650\uFF0830M\uFF09  
  11. #\u6587\u4EF6\u4E0A\u4F20\u5176\u5B83\u9519\u8BEF\u4FE1\u606F    
  12. struts.messages.error.uploading=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u4E0A\u4F20\u7A0B\u5E8F\u53D1\u751F\u5185\u90E8\u9519\u8BEF  




    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多