struts2 多文件上传
以下是使用多线程上传文件的实验版,理想情况下的多文件上传使用针对性开发的组件比较好。
public class UploadFileMutilAction extends ActionSupport {
private File[] file;
private String[] fileFileName;
private String[] fileContentType;
private String path;
@Override
public String execute() throws Exception {
String realPath = ServletActionContext.getServletContext().getRealPath(path);
int poolSize = file.length;
ExecutorService es = Executors.newFixedThreadPool(poolSize);
for (int j = 0; j < poolSize; j++) {
Runnable r = new UploadFileMutilThread(file[j], fileFileName[j], realPath);
es.execute(r);
}
es.shutdown();
return SUCCESS;
}
public File[] getFile() {
return file;
}
public void setFile(File[] file) {
this.file = file;
}
public String[] getFileFileName() {
return fileFileName;
}
public void setFileFileName(String[] fileFileName) {
this.fileFileName = fileFileName;
}
public String[] getFileContentType() {
return fileContentType;
}
public void setFileContentType(String[] fileContentType) {
this.fileContentType = fileContentType;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
public class UploadFileMutilThread implements Runnable {
private File file;
private String FileName;
private String saveDir;
public UploadFileMutilThread(File files, String fileNames, String saveDir) {
this.file = files;
FileName = fileNames;
this.saveDir = saveDir;
}
@Override
public void run() {
File f = new File(saveDir);
if (!f.exists()) {
f.mkdirs();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(new FileOutputStream(new File(f, FileName)));
byte[] b = new byte[2024];
int i = -1;
while ((i = bis.read(b)) != -1) {
bos.write(b);
}
bis.close();
bos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}