在upload.jsp頁面中將多個檔案域物件命名為相同的名字,這樣在action中就可以將多個檔案域解析成一個數組,數組的大小就是檔案域的個數,同時一個檔案域解析成三個對應的變量,因此多個檔案域對應三個數組,其中每個數組的大小就是檔案域的個數。 jsp頁面程式碼如下:
</form>
對應的Action依序遍歷所有檔案域,然後產生對應的輸入檔案流,輸出檔案流在指定的伺服器儲存路徑中新增對應的輸出檔案流保存檔案。同時動態指定伺服器上檔案的儲存路徑。
action程式碼如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String title;
private File[] upload;
private String[] uploadFileName;
private String[] uploadContentType;
private String savePath;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String upload()throws Exception{
File[] files=this.getUpload();
for(int i=0;i<files.length;i++){
FileOutputStream fos=new FileOutputStream(this.getSavePath()+"//"+this.getUploadFileName()[i]);
byte[] buffer=new byte[1024];
FileInputStream fis=new FileInputStream(files[i]);
int len=0;
while((len=fis.read(buffer))>0){
fos.write(buffer,0,len);
}
}
return SUCCESS;
}
}
struts.xml檔案配置如下:設定檔上傳的攔截器,允許的上傳檔案類型,上傳檔案大小限制,同時引入defaultStack攔截器和上傳檔案在伺服器上的儲存位置
</struts>
success.jsp頁面代碼如下: