Struts2教程7:上傳任意多個檔案

來源:互聯網
上載者:User

一、上傳單個檔案

上傳檔案是很多Web程式都具有的功能。在Struts1.x中已經提供了用於上傳檔案的組件。而在Struts2中提供了一個更為容易操作的上傳檔案組件。所不同的是,Struts1.x的上傳組件需要一個ActionForm來傳遞檔案,而Struts2的上傳組件是一個攔截器(這個攔截器不用配置,是自動裝載的)。在本文中先介紹一下如何用struts2上傳單個檔案,最後介紹一下用struts2上傳任意多個檔案。

要用Struts2實現上傳單個檔案的功能非常容易實現,只要使用普通的Action即可。但為了獲得一些上傳檔案的資訊,如上傳檔案名稱、上傳檔案類型以及上傳檔案的Stream對象,就需要按著一定規則來為Action類增加一些getter和setter方法。

在Struts2中,用於獲得和設定java.io.File對象(Struts2將檔案上傳到臨時路徑,並使用java.io.File開啟這個臨時檔案)的方法是getUpload和setUpload。獲得和設定檔案名稱的方法是getUploadFileName和setUploadFileName,獲得和設定上傳檔案內容類型的方法是getUploadContentType和setUploadContentType。下面是用於上傳的動作類的完整代碼:

package action;import java.io.*;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport {    private File upload;    private String uploadFileName;    private String uploadContentType;    public String getUploadFileName()    {        return uploadFileName;    }    public void setUploadFileName(String fileName)    {        this.uploadFileName = fileName;    }    public File getUpload()    {        return upload;    }    public void setUpload(File upload)    {        this.upload = upload;    }    public void setUploadContentType(String contentType)    {        this.uploadContentType=contentType;    }    public String getUploadContentType()    {        return this.uploadContentType;    }    public String execute() throws Exception    {           java.io.InputStream is = new java.io.FileInputStream(upload);        java.io.OutputStream os = new java.io.FileOutputStream("d:\\upload\\" + uploadFileName);        byte buffer[] = new byte[8192];        int count = 0;        while((count = is.read(buffer)) > 0)        {            os.write(buffer, 0, count);        }        os.close();        is.close();        return SUCCESS;    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.