【原創】Struts1.x系列教程(8):上傳單個檔案

銀河使者發表於2009-02-05

本文為原創,如需轉載,請註明作者和出處,謝謝!

    Web程式中的上傳檔案的功能一般會使用標籤在客戶端顯示輸入要上傳的檔名的使用者介面。如果讀者使用過JSP/Servlet來處理客戶端上傳的檔案就會知道,實現這個功能並不是很容易。而在Struts中為我們提供了一種機制,可以非常方便地將客戶端上傳的檔案儲存在服務端。
   
Struts Html標籤庫中提供了一個標籤,可以和FormFile型別的屬性一起使用。通過這個屬性返回的FormFile物件,就可以很方便地獲得上傳檔案的InputStream物件,並做進一步地處理。

    Struts中,一個FormFile物件代表一個上傳的檔案。FormFile實際上是一個介面,我們可以在org.apache.struts.upload包中找到這個介面。FormFile介面有如下五個常用的方法:

    1. getInputStream()方法

    這個方法用於獲得上傳檔案的java.io.InputStream物件,我們可以從這個InputStream物件中讀取上傳檔案的資料,並將其寫到服務端指定的路徑下。

    2. getFileData()方法

    這個方法用於將上傳檔案的整個內容放到一個byte型別的陣列中,如果上傳檔案的尺寸比較小的話,使用這個方法可以很方便地將上傳檔案儲存到在服務端的指定路徑中。
    3. getFileName()方法

    這個方法用於獲得上傳檔案的檔名(不包括檔案在客戶機的路徑部分)。

    4. getFileSize()方法

    這個方法用於獲得上傳檔案的位元組數。

    5. destroy()方法

    用於銷燬所有和當前上傳檔案相關的資源。

   下面的例子演示瞭如何使用標籤和FormFile物件來上傳單個檔案。實現這個例子需要如下六步:

【第1步】建立上傳檔案的JSP頁面
    在目錄中建立一個uploadFile.jsp檔案,程式碼如下:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  @ page pageEncoding="GBK"%>
  
@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
  
<html>
    
<head>
      
<title>上傳單個檔案(檔案大小不能超過2M) title>
    
head>
    
<body>
-- 在<html:form>標籤中必須加enctype="multipart/form-data"  --%>
      
<html:form enctype="multipart/form-data" action="uploadFile"> 
        
<html:file property="myFile"/><p>  -- 使用<html:file>標籤讓使用者輸入上傳檔名  --%>
        
<html:submit value="上傳"/>
      
html:form>
    
body>
  
html>

Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4 【第2步】建立ActionForm的子類

    在"src"actionform目錄中建立一個UploadForm.java檔案,程式碼如下:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  package actionform;
  
  
import org.apache.struts.action.*;
  
import org.apache.struts.upload.FormFile;
  
  
public class UploadForm extends ActionForm
  {  
      
private FormFile myFile;  // 這個myFile代表要上傳的檔案
  
      
public FormFile getMyFile()
      {
          
return myFile;
      }
      
public void setMyFile(FormFile myFile)
      {
          
this.myFile = myFile;
      }
  }

【第3步】建立Struts動作類(Action的子類)

    在Struts中,一般在Struts的動作類中處理上傳的檔案。在"src"action目錄中建立一個UploadAction.java檔案,程式碼如下:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  package action;
  
  
import javax.servlet.http.*;
  
import org.apache.struts.action.*;
  
import org.apache.struts.upload.FormFile;
  
import java.io.*
  
import actionform.*;
  
  
public class UploadAction extends Action
  {
      
protected void saveFile(FormFile formFile) throws Exception
      {
          
// 從web.xml檔案中獲得指定的上傳路徑
          String path = this.getServlet().getServletConfig().getInitParameter("uploadPath");
          InputStream in 
= formFile.getInputStream();   // 獲得上傳檔案的InputStream
          // 在服務端指定的上傳路徑中建立一個空的檔案(檔名為getFileName()方法返回的值)
          FileOutputStream fout = new FileOutputStream(path + formFile.getFileName());   
          
byte buffer[] = new byte[8192];  
          
int count = 0;
          //  開始向上傳路徑中剛建立的檔案寫入資料,每次寫8k位元組
          while ((count = in.read(buffer)) > 0
          {
              fout.write(buffer, 
0, count);
          }
          fout.close();
          formFile.destroy();   
// 上傳成功後,銷燬當前上傳檔案的資源
      }
      
public ActionForward execute(ActionMapping mapping, ActionForm form,
              HttpServletRequest request, HttpServletResponse response)
      {
          UploadForm uForm 
= (UploadForm) form;
          PrintWriter out 
= null;
          
try
          {
              response.setCharacterEncoding(
"GBK");
              out 
= response.getWriter();
              saveFile(uForm.getMyFile());  
// 將上傳檔案儲存到指寫的路徑(在web.xml中配置)
              out.println("上傳檔案成功.");
          }
          
catch (Exception e)
          {
              out.println(e.getMessage());
          }
          
return null;
      }
  }

Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4 Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4 【第4步】配置struts-config.xml
    在這一步來配置一下在第2步和第3步分別建立的ActionForm和Action的子類。開啟struts-config.xml檔案,在中加入如下的子標籤:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt<form-bean name="uploadForm" type="actionform.UploadForm" />   
Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4
   在中加入如下的子標籤:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  <action name="uploadForm" path="/uploadFile" scope="request" type="action.UploadAction" />

Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4 【第5步】設定用於儲存上傳檔案的路徑
    開啟web.xml檔案,找到一個叫action的Servlet(也就是用於處理Struts動作的Servlet),並在中加入如下的子標籤(假設儲存上傳檔案的路徑為D:"upload",路徑的最後一個字元必須是“"”):

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt<init-param>
    
<param-name>uploadPathparam-name>
    
<param-value>D:\upload\param-value>
init-param>

Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4 【第6步】限制上傳檔案的大小
    這一步是可選的,如果不限制上傳檔案的大小,就意味著可以上傳任意大小的檔案。而一般的應用程式,如電子相簿,網路硬碟都會限制上傳檔案的最大尺寸。
    開啟struts-config.xml檔案,在中加入如下的子標籤:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  <controller maxFileSize="2M" />

Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4     上面的標籤將上傳檔案的最大尺寸設為2M,maxFileSize屬性值的單位可以是M,也可以是K或G,如2K,5G等。

    啟動Tomcat後,在IE中輸入如下的URL來測試程式:

http://localhost:8080/samples/uploadFile.jsp

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12921506/viewspace-545325/,如需轉載,請註明出處,否則將追究法律責任。

相關文章