一、上傳單個檔案
上傳檔案是很多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; }}