相比单文件上传,多文件上传只需要在private各种属性的时候,定义成数组
然后在上传的时候使用循环来循环上传
package com.rl.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* action动作类充当模型对象
* @author renliang
*
*/
public class UploadsAction extends ActionSupport{
private String username;
/**
* 要接收的文件,命名需要和表单中的file类型的input的name一致
*/
private File[] upload;
/**
* 文件名的接收 File属性名FileName:固定写法
*/
private String[] uploadFileName;
/**
* 获得上传文件的MIME类型,File属性名字ContentType:固定写法
*/
private String[] uploadContentType;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 upload() throws Exception{
//获得servletContext
ServletContext sc = ServletActionContext.getServletContext();
//获得服务的绝对路径
for(int i = 0; i < upload.length; i++){
String realPath = sc.getRealPath("/");
realPath = realPath + "upload\\"+uploadFileName[i];
//定义输入输出流
FileUtils.copyFile(upload[i], new File(realPath));
}
return super.SUCCESS;
}
}
在struts.xml中的配置
<!-- 多文件上传 -->
<action name="renliangs" class="com.rl.action.UploadsAction" method="upload">
<!--
主动引用默认拦截器栈
-->
<interceptor-ref name="defaultStack">
<!-- 设置上传拦截器fileUpload.allowedExtensions, 不要使用allowedExtensionsSet -->
<param name="fileUpload.allowedExtensions">.png,.txt,jar</param>
</interceptor-ref>
<result name="success">/success.jsp</result>
<result name="input">/form1.jsp</result>
</action>