在Struts 2中實現文件上傳

前一陣子有些朋友在電子郵件中問關於Struts 2實現文件上傳的問題, 所以今天我們就來討論一下這個問題。

實現原理

Struts 2是通過Commons FileUpload文件上傳。Commons FileUpload通過將HTTP的數據保存到臨時文件夾,然後Struts使用fileUpload攔截器將文件綁定到Action的實例中。從而我們就能夠以本地文件方式的操作瀏覽器上傳的文件。

具體實現

前段時間Apache發佈了Struts 2.0.6 GA,所以本文的實現是以該版本的Struts作爲框架的。以下是例子所依賴類包的列表:
依賴類包的列表 
清單1 依賴類包的列表
首先,創建文件上傳頁面FileUpload.jsp,內容如下:
<% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %>
<% @ taglib prefix = " s " uri = " /struts-tags " %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
   
< title > Struts 2 File Upload </ title >
</ head >
< body >
   
< s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >
       
< s:file name ="myFile" label ="Image File" />
       
< s:textfield name ="caption" label ="Caption" />        
       
< s:submit />
   
</ s:form >
</ body >
</ html >
清單2 FileUpload.jsp
在FileUpload.jsp中,先將表單的提交方式設爲POST,然後將enctype設爲multipart/form-data,這並沒有什麼特別之處。接下來,<s:file/>標誌將文件上傳控件綁定到Action的myFile屬性。
其次是FileUploadAction.java代碼:
package tutorial;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {
   
private static final long serialVersionUID = 572146812454l ;
   
private static final int BUFFER_SIZE = 16 * 1024 ;
   
   
private File myFile;
   
private String contentType;
   
private String fileName;
   
private String p_w_picpathFileName;
   
private String caption;
   
   
public void setMyFileContentType(String contentType) {
       
this .contentType = contentType;
   }

   
   
public void setMyFileFileName(String fileName) {
       
this .fileName = fileName;
   }

       
   
public void setMyFile(File myFile) {
       
this .myFile = myFile;
   }

   
   
public String getImageFileName() {
       
return p_w_picpathFileName;
   }

   
   
public String getCaption() {
       
return caption;
   }


   
public void setCaption(String caption) {
       
this .caption = caption;
   }

   
   
private static void copy(File src, File dst) {
       
try {
           InputStream in
= null ;
           OutputStream out
= null ;
           
try {                
               in
= new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
               out
= new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
               
byte [] buffer = new byte [BUFFER_SIZE];
               
while (in.read(buffer) > 0 ) {
                   out.write(buffer);
               }

           }
finally {
               
if ( null != in) {
                   in.close();
               }

               
if ( null != out) {
                   out.close();
               }

           }

       }
catch (Exception e) {
           e.printStackTrace();
       }

   }

   
   
private static String getExtention(String fileName) {
       
int pos = fileName.lastIndexOf( " . " );
       
return fileName.substring(pos);
   }


   @Override
   
public String execute()     {        
       p_w_picpathFileName
= new Date().getTime() + getExtention(fileName);
       File p_w_picpathFile
= new File(ServletActionContext.getServletContext().getRealPath( " /UploadImages " ) + " / " + p_w_picpathFileName);
       copy(myFile, p_w_picpathFile);
       
return SUCCESS;
   }

   
}
清單3 tutorial/FileUploadAction.java
在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文件夾下,新文件的名稱是由系統時間與上傳文件的後綴組成,該名稱將被賦給p_w_picpathFileName屬性,以便上傳成功的跳轉頁面使用。
下面我們就來看看上傳成功的頁面:
<% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %>
<% @ taglib prefix = " s " uri = " /struts-tags " %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
   
< title > Struts 2 File Upload </ title >
</ head >
< body >
   
< div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >
       
< img src ='UploadImages/<s:property value ="p_w_picpathFileName" /> ' />
       
< br />
       
< s:property value ="caption" />
   
</ div >
</ body >
</ html >
清單4 ShowUpload.jsp
ShowUpload.jsp獲得p_w_picpathFileName,將其UploadImages組成URL,從而將上傳的圖像顯示出來。
然後是Action的配置文件:
<? xml version="1.0" encoding="UTF-8" ?>

<! DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd"
>

< struts >
   
< package name ="fileUploadDemo" extends ="struts-default" >
       
< action name ="fileUpload" class ="tutorial.FileUploadAction" >
           
< interceptor-ref name ="fileUploadStack" />
           
< result name ="success" > /ShowUpload.jsp </ result >
       
</ action >
   
</ package >
</ struts >
清單5 struts.xml
fileUpload Action顯式地應用fileUploadStack的攔截器。
最後是web.xml配置文件:
<? xml version="1.0" encoding="UTF-8" ?>
< web-app id ="WebApp_9" version ="2.4"
    xmlns
="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee [url]http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd[/url]" >

   
< display-name > Struts 2 Fileupload </ display-name >

   
< filter >
       
< filter-name > struts-cleanup </ filter-name >
       
< filter-class >
            org.apache.struts2.dispatcher.ActionContextCleanUp
       
</ filter-class >
   
</ filter >
    
   
< filter >
       
< filter-name > struts2 </ filter-name >
       
< filter-class >
            org.apache.struts2.dispatcher.FilterDispatcher
       
</ filter-class >
   
</ filter >
    
   
< filter-mapping >
       
< filter-name > struts-cleanup </ filter-name >
       
< url-pattern > /* </ url-pattern >
   
</ filter-mapping >

   
< filter-mapping >
       
< filter-name > struts2 </ filter-name >
       
< url-pattern > /* </ url-pattern >
   
</ filter-mapping >

   
< welcome-file-list >
       
< welcome-file > index.html </ welcome-file >
   
</ welcome-file-list >

</ web-app >
清單6 WEB-INF/web.xml
發佈運行應用程序,在瀏覽器地址欄中鍵入:[url]http://localhost:8080/Struts2_Fileupload/FileUpload.jsp[/url],出現圖示頁面:

清單7 FileUpload頁面
選擇圖片文件,填寫Caption並按下Submit按鈕提交,出現圖示頁面:

清單8 上傳成功頁面

更多配置

在運行上述例子,如果您留心一點的話,應該會發現服務器控制檯有如下輸出:
Mar 20 , 2007 4 : 08 : 43 PM org.apache.struts2.dispatcher.Dispatcher getSaveDir
INFO: Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir
Mar
20 , 2007 4 : 08 : 43 PM org.apache.struts2.interceptor.FileUploadInterceptor intercept
INFO: Removing file myFile C:\Program Files\Tomcat
5.5 \work\Catalina\localhost\Struts2_Fileupload\upload_251447c2_1116e355841__7ff7_00000006.tmp
清單9 服務器控制檯輸出
上述信息告訴我們,struts.multipart.saveDir沒有配置。struts.multipart.saveDir用於指定存放臨時文件的文件夾,該配置寫在struts.properties文件中。例如,如果在struts.properties文件加入如下代碼:
struts.multipart.saveDir = /tmp
清單10 struts配置
這樣上傳的文件就會臨時保存到你根目錄下的tmp文件夾中(一般爲c:\tmp),如果此文件夾不存在,Struts 2會自動創建一個。

錯誤處理

上述例子實現的圖片上傳的功能,所以應該阻止用戶上傳非圖片類型的文件。在Struts 2中如何實現這點呢?其實這也很簡單,對上述例子作如下修改即可。
首先修改FileUpload.jsp,在<body>與<s:form>之間加入“<s:fielderror />”,用於在頁面上輸出錯誤信息。
然後修改struts.xml文件,將Action fileUpload的定義改爲如下所示:
        < action name ="fileUpload" class ="tutorial.FileUploadAction" >
           
< interceptor-ref name ="fileUpload" >
               
< param name ="allowedTypes" >
                    p_w_picpath/bmp,p_w_picpath/png,p_w_picpath/gif,p_w_picpath/jpeg
               
</ param >
           
</ interceptor-ref >
           
< interceptor-ref name ="defaultStack" />            
           
< result name ="input" > /FileUpload.jsp </ result >
           
< result name ="success" > /ShowUpload.jsp </ result >
       
</ action >
清單11 修改後的配置文件
顯而易見,起作用就是fileUpload攔截器的allowTypes參數。另外,配置還引入defaultStack它會幫我們添加驗證等功能,所以在出錯之後會跳轉到名稱爲“input”的結果,也即是FileUpload.jsp。
發佈運行應用程序,出錯時,頁面如下圖所示:

清單12 出錯提示頁面
上面的出錯提示是Struts 2默認的,大多數情況下,我們都需要自定義和國際化這些信息。通過在全局的國際資源文件中加入“struts.messages.error.content.type.not.allowed=The file you uploaded is not a p_w_picpath”,可以實現以上提及的需求。對此有疑問的朋友可以參考我之前的文章《在Struts 2.0中國際化(i18n)您的應用程序》。
實現之後的出錯頁面如下圖所示:

清單13 自定義出錯提示頁面
同樣的做法,你可以使用參數“maximumSize”來限制上傳文件的大小,它對應的字符資源名爲:“struts.messages.error.file.too.large”。
字符資源“struts.messages.error.uploading”用提示一般的上傳出錯信息。

多文件上傳

與單文件上傳相似,Struts 2實現多文件上傳也很簡單。你可以將多個<s:file />綁定Action的數組或列表。如下例所示。
< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >
   
< s:file label ="File (1)" name ="upload" />
   
< s:file label ="File (2)" name ="upload" />
   
< s:file label ="FIle (3)" name ="upload" />
   
< s:submit />
</ s:form >
清單14 多文件上傳JSP代碼片段
如果你希望綁定到數組,Action的代碼應類似:
    private File[] uploads;
   
private String[] uploadFileNames;
   
private String[] uploadContentTypes;

   
public File[] getUpload() { return this .uploads; }
   
public void setUpload(File[] upload) { this .uploads = upload; }

   
public String[] getUploadFileName() { return this .uploadFileNames; }
   
public void setUploadFileName(String[] uploadFileName) { this .uploadFileNames = uploadFileName; }

   
public String[] getUploadContentType() { return this .uploadContentTypes; }
   
public void setUploadContentType(String[] uploadContentType) { this .uploadContentTypes = uploadContentType; }
清單15 多文件上傳數組綁定Action代碼片段
如果你想綁定到列表,則應類似:
    private List < File > uploads = new ArrayList < File > ();
   
private List < String > uploadFileNames = new ArrayList < String > ();
   
private List < String > uploadContentTypes = new ArrayList < String > ();

   
public List < File > getUpload() {
       
return this .uploads;
   }

   
public void setUpload(List < File > uploads) {
       
this .uploads = uploads;
   }


   
public List < String > getUploadFileName() {
       
return this .uploadFileNames;
   }

   
public void setUploadFileName(List < String > uploadFileNames) {
       
this .uploadFileNames = uploadFileNames;
   }


   
public List < String > getUploadContentType() {
       
return this .uploadContentTypes;
   }

   
public void setUploadContentType(List < String > contentTypes) {
       
this .uploadContentTypes = contentTypes;
   }
清單16 多文件上傳列表綁定Action代碼片段

總結

在Struts 2中實現文件上傳的確是輕而易舉,您要做的只是使用<s:file />與Action的屬性綁定。這又一次有力地證明了Struts 2的簡單易用。
 
[例二]
 
Struts2使用開源項目Apache Jakarta Commons FileUpload和內建的FileUploadInterceptor攔截器實現文件上傳,所需的jar包如下:
commons-logging-1.1.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.6.jar
xwork-2.0.1.jar
commons-io-1.3.1.jar
commons-fileupload-1.2.jar
★ 文件上傳頁面 fileupload.jsp
  1. <%@ page language="java" contentType="text/html; charset=GBK"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3.   
  4. <html>  
  5.   <head>  
  6.   <head>  
  7.      
  8.   <body>  
  9.     <s:form action="fileUpload" method="post" enctype="multipart/form-data">  
  10.       <s:file name="doc" label="File"/>  
  11.       <s:submit/>  
  12.     <s:form>  
  13.   <body>  
  14. <html>  
這裏需要注意的是,form的enctype屬性必須設置爲multipart/form-data。
★ 處理文件上傳 FileUploadAction.java
  1. package fileupload;   
  2.   
  3. import java.io.File;   
  4. import java.text.DateFormat;   
  5. import java.text.SimpleDateFormat;   
  6. import java.util.Date;   
  7. import java.util.Random;   
  8.   
  9. import javax.servlet.ServletContext;   
  10.   
  11. import org.apache.commons.io.FileUtils;   
  12. import org.apache.struts2.util.ServletContextAware;   
  13.   
  14. import com.opensymphony.xwork2.ActionSupport;   
  15.   
  16. public class FileUploadAction extends ActionSupport implements ServletContextAware {   
  17.        
  18.     private static final long serialVersionUID = -5016873153441103539L;   
  19.        
  20.     private File doc;   
  21.     private String fileName;   
  22.     private String contentType;   
  23.        
  24.     private ServletContext context;   
  25.            
  26.     public void setDoc(File file) {   
  27.         this.doc = file;   
  28.     }   
  29.        
  30.     public void setDocFileName(String fileName) {   
  31.         this.fileName = fileName;   
  32.     }   
  33.        
  34.     public void setDocContentType(String contentType) {   
  35.         this.contentType = contentType;   
  36.     }   
  37.        
  38.     public void setServletContext(ServletContext context) {   
  39.         this.context = context;   
  40.     }   
  41.        
  42.     public String execute() throws Exception {   
  43.         String targetDirectory = context.getRealPath("/upload");   
  44.         String targetFileName = generateFileName(fileName);   
  45.         File target = new File(targetDirectory, targetFileName);   
  46.            
  47.         FileUtils.copyFile(doc, target);   
  48.            
  49.         return SUCCESS;   
  50.     }   
  51.        
  52.     private String generateFileName(String fileName) {   
  53.         DateFormat format = new SimpleDateFormat("yyMMddHHmmss");   
  54.         String formatDate = format.format(new Date());   
  55.            
  56.         int random = new Random().nextInt(10000);   
  57.            
  58.         int position = fileName.lastIndexOf(".");   
  59.         String extension = fileName.substring(position);   
  60.            
  61.         return formatDate + random + extension;   
  62.     }      
  63. }  
在fileupload.jsp中,只有doc一個字段,而FileUploadAction.java中,卻有三個字段,Struts2怎麼通過頁面的一個字段設置Action裏的三個字段呢?沒錯,這就是FileUploadInterceptor的功勞了!你所要做的只是按照一定的樣式命名這三個字段的set方法,而字段名可以任意命名。第一個File類型的字段的set方法還是以常規的方式命名,另兩個String類型的字段的set方法必須分別以“File字段的set方法名+FileName”和“File字段的set方法名+ContentType”來命名。
★ 配置文件 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.     <package name="fileupload" namespace="/fileupload" extends="struts-default">  
  9.            
  10.         <action name="fileUpload" class="fileupload.FileUploadAction">  
  11.             <result>/fileupload/upload_success.jsp</result>  
  12.         </action>  
  13.        
  14.     </package>  
  15.   
  16. </struts>  
★ 配置文件 web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"    
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
  6.     [url]http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd[/url]">  
  7.        
  8.     <filter>  
  9.         <filter-name>struts-cleanup</filter-name>  
  10.         <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>  
  11.     </filter>  
  12.        
  13.     <filter>  
  14.         <filter-name>struts2</filter-name>  
  15.         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
  16.     </filter>  
  17.        
  18.     <filter-mapping>  
  19.         <filter-name>struts-cleanup</filter-name>  
  20.         <url-pattern>/*</url-pattern>  
  21.     </filter-mapping>  
  22.        
  23.     <filter-mapping>  
  24.         <filter-name>struts2</filter-name>  
  25.         <url-pattern>/*</url-pattern>  
  26.     </filter-mapping>  
  27.   
  28. </web-app>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章