strut2

描述:

通过struts2实现多图片上传。

我使用的版本是2.2.1,使用的包有如下几个:

strut2_第1张图片

        具体实现:

      1. 创建上传图片的页面

fileUpload.jsp

[java] 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. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  8. <html> 
  9.   <head> 
  10.     <base href="<%=basePath%>"> 
  11.     <title>My JSP 'fileUpLoad.jsp' starting page</title> 
  12.      <meta http-equiv="pragma" content="no-cache"> 
  13.      <meta http-equiv="cache-control" content="no-cache"> 
  14.      <meta http-equiv="expires" content="0">     
  15.      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
  16.      <meta http-equiv="description" content="This is my page"> 
  17.      <!-- 
  18.      <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> 
  19.      --> 
  20.   </head> 
  21.   <body> 
  22.              <center> 
  23.                   <s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" > 
  24.                   <s:fielderror /> 
  25.                   <s:file name ="myFile" label ="Image File1"/> 
  26.                   <s:file name ="myFile" label ="Image File2"/> 
  27.                   <s:file name ="myFile" label ="Image File3"/> 
  28.                   <s:textfield name ="caption" label ="Caption" /> 
  29. <s:submit/> 
  30.                     </s:form>   
  31.               </center> 
  32.   </body> 
  33. </html> 

在FileUpload.jsp中,先将表单的提交方式设为POST,然后将enctype设为multipart/form-data,这并没有什么特别之处。接下来,<s:file/>标志将文件上传控件绑定到Action的myFile属性,因为要上传多张图片我们就暂且添加三个file

注意这三个file的name属性要相同。

2. 创建处理图片上传的action

FileUploadAction.java

[java] view plaincopy

  1. package com.ywjava.action; 
  2. import java.io.BufferedInputStream; 
  3. import java.io.BufferedOutputStream; 
  4. import java.io.File; 
  5. import java.io.FileInputStream; 
  6. import java.io.FileOutputStream; 
  7. import java.io.InputStream; 
  8. import java.io.OutputStream; 
  9. import java.util.ArrayList; 
  10. import java.util.Date; 
  11. import java.util.List; 
  12. import org.apache.struts2.ServletActionContext; 
  13. import com.opensymphony.xwork2.ActionSupport; 
  14. public class FileUploadAction extends ActionSupport { 
  15. private static final long serialVersionUID = 572146812454l; 
  16. private static final int BUFFER_SIZE = 16 * 1024; 
  17. private List<File> myFile = new ArrayList<File>();   
  18. private List<String> contentType = new ArrayList<String>(); 
  19. private List<String> fileName = new ArrayList<String>();    //文件名
  20. private List<String> imageFileName = new ArrayList<String>(); 
  21. private String caption; 
  22. private static void copy(File src, File dst) { 
  23. try { 
  24.             InputStream in = null; 
  25.             OutputStream out = null; 
  26. try { 
  27.                 in = new BufferedInputStream(new FileInputStream(src), 
  28.                         BUFFER_SIZE); 
  29.                 out = new BufferedOutputStream(new FileOutputStream(dst), 
  30.                         BUFFER_SIZE); 
  31. byte[] buffer = new byte[BUFFER_SIZE]; 
  32. while (in.read(buffer) > 0) { 
  33.                     out.write(buffer); 
  34.                 } 
  35.             } finally { 
  36. if (null != in) { 
  37.                     in.close(); 
  38.                 } 
  39. if (null != out) { 
  40.                     out.close(); 
  41.                 } 
  42.             } 
  43.         } catch (Exception e) { 
  44.             e.printStackTrace(); 
  45.         } 
  46.     } 
  47. private static String getExtention(String fileName) { 
  48. int pos = fileName.lastIndexOf("."); 
  49. return fileName.substring(pos); 
  50.     } 
  51. @Override
  52. public String execute() { 
  53. if (myFile == null) 
  54. return INPUT; 
  55. for (int i = 0; i < myFile.size(); i++) { 
  56.             imageFileName.add(new Date().getTime()+ getExtention(this.getMyFileFileName().get(i))) ; 
  57.             File imageFile = new File(ServletActionContext.getServletContext()  //得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
  58.                     .getRealPath("UploadImages")    
  59.                     + "/" + imageFileName);  
  60.             copy(myFile.get(i), imageFile);  //把图片写入到上面设置的路径里
  61.         } 
  62. return SUCCESS; 
  63.     } 
  64. public List<File> getMyFile() { 
  65. return myFile; 
  66.     } 
  67. public void setMyFile(List<File> myFile) { 
  68. this.myFile = myFile; 
  69.     } 
  70. public List<String> getContentType() { 
  71. return contentType; 
  72.     } 
  73. public void setContentType(List<String> contentType) { 
  74. this.contentType = contentType; 
  75.     } 
  76. public List<String> getMyFileFileName() { 
  77. return fileName; 
  78.     } 
  79. public void setMyFileFileName(List<String> fileName) { 
  80. this.fileName = fileName; 
  81.     } 
  82. public List<String> getImageFileName() { 
  83. return imageFileName; 
  84.     } 
  85. public void setImageFileName(List<String> imageFileName) { 
  86. this.imageFileName = imageFileName; 
  87.     } 
  88. public String getCaption() { 
  89. return caption; 
  90.     } 
  91. public void setCaption(String caption) { 
  92. this.caption = caption; 
  93.     } 
  94. public static int getBufferSize() { 
  95. return BUFFER_SIZE; 
  96.     } 

在FileUploadAction中我分别写了setMyFileContentType、setMyFileFileName、setMyFile和setCaption四个Setter方法,

后两者很容易明白,分别对应FileUpload.jsp中的<s:file/>和<s:textfield/>标志。但是前两者并没有显式地与任何的页面标志绑定,

那么它们的值又是从何而来的呢?其实,<s:file/>标志不仅仅是绑定到myFile,

还有myFileContentType(上传文件的MIME类型)和myFileFileName(上传文件的文件名,该文件名不包括文件的路径)。

因此,<s:file name="xxx" />对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。

        FileUploadAction作用是将浏览器上传的文件拷贝到WEB应用程序的

UploadImages文件夹下,新文件的名称是由系统时间与上传文件的后缀组成,

     该名称将被赋给imageFileName属性,以便上传成功的跳转页面使用。

3. 创建显示图片的页面

       showUpload.jsp

[java] 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.     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">                                         
  8.     <html>                                                                                                  
  9.       <head>                                                                                                
  10.         <base href="<%=basePath%>">                                                                         
  11.         <title>Show Image</title>                                                                             
  12.         <meta http-equiv="pragma" content="no-cache">                                                           
  13.         <meta http-equiv="cache-control" content="no-cache">                                                    
  14.         <meta http-equiv="expires" content="0">                                                                 
  15.         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">                                       
  16.         <meta http-equiv="description" content="This is my page">                                               
  17.         <!--                                                                                                    
  18.         <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">                                               
  19.         -->                                                                                                     
  20.       </head>                                                                                                 
  21.       <body>                                                                                                  
  22.       <s:iterator value="imageFileName" status="length">                                                      
  23.             <div                                                                                                  
  24.                 style="padding: 3px; border: solid 1px #cccccc; text-align: center">                                
  25.                 <img src='UploadImages/<s:property value ="imageFileName" /> ' />                                   
  26.                 <br />                                                                                              
  27.                 <s:property value="caption" />                                                                      
  28.             </div>                                                                                                
  29.             </s:iterator>                                                                                         
  30.             <s:property value ="caption" />                                                                       
  31.         </body>                                                                                                 
  32.     </html>                                                                                                   

4.Action配置文件

Struts.xml

[java] view plaincopy

  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.enable.DynamicMethodInvocation" value="false" /> 
  7.     <constant name="struts.devMode" value="false" /> 
  8.     <!-- 指定国际化资源文件的baseName为messageResource --> 
  9.     <constant name="struts.custom.i18n.resources" value="messageResource" /> 
  10.     <!-- 设置该应用使用的解码集 --> 
  11.     <constant name="struts.i18n.encoding" value="utf-8" /> 
  12.     <!-- 上传的全部图片的最大限制--> 
  13.     <constant name="struts.multipart.maxSize" value="1024102400" /> 
  14.     <!-- 临时存放文件的路径 --> 
  15.     <constant name="struts.multipart.saveDir" value="d:/test" /> 
  16.     <package name="index" namespace="/" extends="struts-default"> 
  17.         <action name="index" class="com.ywjava.action.IndexAction"> 
  18.             <result> 
  19.                 /WEB-INF/page/fileUpLoad.jsp 
  20.             </result> 
  21.         </action> 
  22.         <action name="fileUpload" class="com.ywjava.action.FileUploadAction"> 
  23.             <!-- 限制图片的格式和图片的大小 --> 
  24.             <interceptor-ref name="fileUpload"> 
  25.                 <param name="allowedTypes"> 
  26.                   image/bmp,image/png,image/gif,image/jpeg,image/pjpeg 
  27.                 </param> 
  28.             </interceptor-ref> 
  29.             <!-- 默认的拦截器,必须要写 --> 
  30.             <interceptor-ref name="defaultStack" /> 
  31.              <result name="input"> /WEB-INF/page/fileUpLoad.jsp</result> 
  32.             <result name="success">/WEB-INF/page/showUpload.jsp</result> 
  33.         </action> 
  34.     </package> 
  35.     <!-- 
  36.         <constant name="struts.multipart.saveDir" value="d:/test"></constant> 
  37.     --> 
  38.     <!-- Add packages here --> 
  39. </struts> 

Action配置文件里所做的配置都有注释,不明白的地方看下注释

另外因为做了国际化处理所以需要一个国际化配置的文件

放在src目录下

5.国际化配置文件

messageResource_zh_CN.properties(只配置了中文的)

struts.messages.error.content.type.not.allowed=/u4E0A/u4F20/u7C7B/u578B/u9519/u8BEF

struts.messages.error.file.too.large=/u4E0A/u4F20/u6587/u4EF6/u592A/u5927

总结:struts2上传图片利用了fileUpload拦截器而变的简单,主要是在action中做相应处理获取文件的相应信息。

你可能感兴趣的:(strut2)