和单文件上传一样,多文件上传只不过是更改一下表单和Action代码而已,前面的东西不再累述,配置什么的都是一
样的,关键就是在Action中,针对的File必须写成数组形式或者说是List形式也是可以的。下面直接看一下代码
package com.bird.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";
}
}
可以看到,除了下面的对文件的遍历和建立目录是不一样的,其他的收拾没问题的,然后再看一下表单的实现,
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'fileUpload.jsp' starting page</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/test/fileupload.action" enctype="multipart/form-data" method="post">
选择文件1:<input type="file" name="image">
选择文件2:<input type="file" name="image">
选择文件3:<input type="file" name="image">
<input type="submit" value="上传">
</form>
</body>
</html>
需要几个文件弄一个就行了,其实很简单。