一、大家都知道用Struts2框架上傳單個文件非常的簡單,其實多文件上傳也一樣,只不過是更改一下表單和Action代碼而已,基本配置不在展示。
關鍵就是在Action中,針對的File必須寫成數組形式或者說是List形式也是可以的。下面直接看一下代碼
package com.qianyan.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
public class FileUpload {
private File[] image; //獲取上傳文件
private String[] imageFileName; //獲取上傳文件名稱
private String[] imageContentType; //獲取上傳文件類型
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
public String execute() throws Exception{
String path = ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(path);
if(image != null){
File savedir = new File(path);
if(!savedir.exists()) savedir.mkdirs();
for(int i = 0; i < image.length; i++){
File saveFile = new File(savedir,imageFileName[i]);
FileUtils.copyFile(image[i], saveFile);
}
}
return "success";
}
}