Struts2實現多文件上傳

描述:

         通過struts2實現多圖片上傳。

         我使用的版本是2.2.1,使用的包有如下幾個:

                   

        具體實現:

      1.       創建上傳圖片的頁面:fileUpload.jsp

 

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2.   
  3. <%@ taglib prefix="s" uri="/struts-tags" %>  
  4.   
  5. <%  
  6.   
  7. String path = request.getContextPath();  
  8.   
  9. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  10.   
  11. %>  
  12.   
  13.    
  14.   
  15. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  16.   
  17. <html>  
  18.   
  19.   <head>  
  20.   
  21.     <base href="<%=basePath%>">  
  22.   
  23.       
  24.   
  25.     <title>My JSP 'fileUpLoad.jsp' starting page</title>  
  26.   
  27.       
  28.   
  29.      <meta http-equiv="pragma" content="no-cache">  
  30.   
  31.      <meta http-equiv="cache-control" content="no-cache">  
  32.   
  33.      <meta http-equiv="expires" content="0">      
  34.   
  35.      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  36.   
  37.      <meta http-equiv="description" content="This is my page">  
  38.   
  39.      <!--  
  40.   
  41.      <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">  
  42.   
  43.      -->  
  44.   
  45.    
  46.   
  47.   </head>  
  48.   
  49.     
  50.   
  51.   <body>  
  52.   
  53.              <center>  
  54.   
  55.                   <s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >  
  56.   
  57.                   <s:fielderror />  
  58.   
  59.                   <s:file name ="myFile" label ="Image File1"/>  
  60.   
  61.                   <s:file name ="myFile" label ="Image File2"/>  
  62.   
  63.                   <s:file name ="myFile" label ="Image File3"/>  
  64.   
  65.                   <s:textfield name ="caption" label ="Caption" />  
  66.   
  67. <s:submit/>  
  68.   
  69.                     </s:form>    
  70.   
  71.               </center>  
  72.   
  73.   </body>  
  74.   
  75. </html>  
  76.   
  77.    

         FileUpload.jsp中,先將表單的提交方式設爲POST,然後將enctype設爲multipart/form-data,這並沒有什麼特別之處。接下來,<s:file/>標誌將文件上傳控件綁定到Action的myFile屬性,因爲要上傳多張圖片我們就暫且添加三個file

注意這三個file的name屬性要相同。

2.    創建處理圖片上傳的action:FileUploadAction.java

 

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

 

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

  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>Show Image</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" mce_href="styles.css">                                                
  22.         -->                                                                                                      
  23.                                                                                                                
  24.       </head>                                                                                                  
  25.                                                                                                                
  26.       <body>                                                                                                   
  27.       <s:iterator value="imageFileName" status="length">                                                       
  28.                                                                                                                
  29.             <div                                                                                                   
  30.                 style="padding: 3px; border: solid 1px #cccccc; text-align: center">                                 
  31.                 <img src='UploadImages/<s:property value ="imageFileName" /> ' />                                    
  32.                 <br />                                                                                               
  33.                 <s:property value="caption" />                                                                       
  34.             </div>                                                                                                 
  35.             </s:iterator>                                                                                          
  36.             <s:property value ="caption" />                                                                        
  37.                                                                                                                    
  38.         </body>                                                                                                  
  39.     </html>                                                                                                    

 

4.Action配置文件:Struts.xml  

 

  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.   
  6. <struts>  
  7.   
  8.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
  9.     <constant name="struts.devMode" value="false" />  
  10.   
  11.     <!-- 指定國際化資源文件的baseName爲messageResource -->  
  12.     <constant name="struts.custom.i18n.resources" value="messageResource" />  
  13.   
  14.     <!-- 設置該應用使用的解碼集 -->  
  15.     <constant name="struts.i18n.encoding" value="utf-8" />  
  16.   
  17.     <!-- 上傳的全部圖片的最大限制-->  
  18.     <constant name="struts.multipart.maxSize" value="1024102400" />  
  19.       
  20.     <!-- 臨時存放文件的路徑 -->  
  21.     <constant name="struts.multipart.saveDir" value="d:/test" />  
  22.       
  23.     <package name="index" namespace="/" extends="struts-default">  
  24.   
  25.         <action name="index" class="com.ywjava.action.IndexAction">  
  26.             <result>  
  27.                 /WEB-INF/page/fileUpLoad.jsp  
  28.             </result>  
  29.         </action>  
  30.   
  31.   
  32.   
  33.         <action name="fileUpload" class="com.ywjava.action.FileUploadAction">  
  34.             <!-- 限制圖片的格式和圖片的大小 -->  
  35.             <interceptor-ref name="fileUpload">  
  36.                 <param name="allowedTypes">  
  37.                   image/bmp,image/png,image/gif,image/jpeg,image/pjpeg  
  38.                 </param>  
  39.             </interceptor-ref>  
  40.             <!-- 默認的攔截器,必須要寫 -->  
  41.             <interceptor-ref name="defaultStack" />  
  42.              <result name="input"> /WEB-INF/page/fileUpLoad.jsp</result>  
  43.             <result name="success">/WEB-INF/page/showUpload.jsp</result>  
  44.   
  45.         </action>  
  46.     </package>  
  47.     <!--  
  48.         <constant name="struts.multipart.saveDir" value="d:/test"></constant>  
  49.     -->  
  50.   
  51.     <!-- Add packages here -->  
  52.   
  53. </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中做相應處理獲取文件的相應信息。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章