Struts2架構的檔案上傳--common-fileupload

來源:互聯網
上載者:User

Struts2架構預設使用了Common-fileUpload組件,該組件將解析出HttpservletRequest請求中的檔案域資訊,並使用IO資料流的方式,將檔案儲存在伺服器的指定位置,完成檔案

 上傳。

1、    Commons-IO是一個非常有用的IO工具包,主要包括下面3個方面:

Utility classes:提供靜態方法來完成通用的任務。

Filters:提供豐富功能的檔案過濾器。

Streams:執行reader和writer有用的Stream。

 

2、    檔案上傳的JSP頁面

在JSP中,form標籤的enctype屬性應設定為multipart/form-data。

Form表單的enctype屬性用來指定表單資料的編碼方式,有如下3個:

 application/x-www-form-urlencoded:如果指定該值,則表單中的資料被編碼為Key-Value對,即預設的編碼方式。

 multipart/form-data:即使用mine編碼,會以二進位流的方式來處理表單資料,檔案上傳需要使用該編碼方式。

 text/plain:表單資料以純文字形式進行編碼,其中不含任何控制項或格式符。

 

3、    檔案上傳的Action

      public class FileUploadAction extends ActionSupport {   

  private File doc;//封裝上傳檔案的屬性

  private String fileName;//封裝上傳檔案的名稱屬性

  private String contentType;//封裝上傳檔案的類型屬性

  private String dir;//儲存檔案路徑屬性

  private String targetFileName;//儲存檔案名稱屬性

 

  public void setDoc(File file) {

         this.doc = file;

  }

  public void setDocFileName(String fileName) {

         this.fileName = fileName;

  }

  public void setDocContentType(String contentType) {

         this.contentType = contentType;

  }

    ……省略部分getter和setter方法

 

    public String execute() throws Exception{

      String realPath = ServletActionContext.getRequest().getRealPath("/upload");

      String targetDirectory=realPath;

      targetFileName=generateFileName(fileName);//產生儲存檔案的名稱

      setDir(targetDirectory+"//"+targetFileName);//儲存檔案的路徑

      File target=new File(targetDirectory,targetFileName);//建立一個目標檔案

      FileUtils.copyFile(doc, target);//將臨時檔案複製到目標檔案

     

         return SUCCESS;

     

    }

     //為上傳檔案自動分配檔案名稱,避免重複

   private String generateFileName(String fileName){

      DateFormat format=new SimpleDateFormat("yyMMddHHmmss");

      String formatDate=format.format(new Date());

      int random=new Random().nextInt(10000);//隨即組建檔案編號

      int position=fileName.lastIndexOf(".");//得到檔案名稱中"."的位置

      System.out.println(fileName);

      System.out.println(position);

      String extension=fileName.substring(position);//得到檔案的副檔名

      System.out.println(extension);

      return formatDate+random+extension;

        

    }

 

}

 

  該Action中定義了一個File類型的doc屬性,用來對應JSP中表單中檔案域的name值。同時定義了兩個非常重要的屬性:fileName和contentType,這三個屬性封裝了檔案上傳的相關資訊:

   File類型的doc屬性封裝了該檔案域對應的檔案內容。

   String類型的fileName屬性封裝了該檔案域對應的檔案名稱。

      String類型的contentType屬性封裝了該檔案域對應的檔案類型。

 

     注意: 實際上Action中是使用setter來封裝檔案域的3個參數的。如果該檔案域name值 

   為xxx,則Action中使用setXxx()來封裝File類型的檔案內容;使用setXxxFileName()來

   封裝檔案名稱;使用setXxxContentType()來封裝檔案類型。只要Action定義了上面的3

   個方法,就能夠在execute()方法中獲得相關資訊。

 

最好在struts.properties中定義如下常量:

   struts.multipart.saveDir= /tmp

這樣上傳的檔案就會臨時儲存到伺服器根目錄下的tmp檔案夾中,如果檔案夾不存在,Struts2會自動建立一個。

 

4、    上傳檔案過濾

為了防止使用者上傳木馬等病毒,需要限制上傳檔案的檔案類型;為了防止伺服器空間不足,需要限制使用者上傳檔案的大小等。

  Struts2架構內建了一個檔案上傳攔截器。該檔案上傳攔截器名稱為fileUpload,只要在配置Action時引用該攔截器就可以實現相應的檔案過濾。  以下為樣本:

  <action name="upload" class="fileUpLoad.FileUploadAction">

        <interceptor-ref name="fileUpload">

        <!—allowedTypes參數指定允許上傳的檔案類型 -->

           <param name="allowedTypes">

                text/plain,            iamge/bmp,image/ppng,image/pjpeg,iamge/gif,image/pjpeg,image/tiff

           </param>

           <!—maximumSize 參數指定了上傳檔案的最大容量(單位位元組)-->

           <param name="maximumSize">10000000</param>

        </interceptor-ref>

        <interceptor-ref name="defaultStack"></interceptor-ref>

        <result name="success">/fileUpLoad/uploadSuccess.jsp</result>

        <result name="input">/fileUpLoad/fileUpload.jsp</result>

     </action>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.