页面:
<form action="multiFileUpload" method="post" enctype="multipart/form-data">
选择第一个文件:<input type="file" name="upload" size="50" /><br />
选择第二个文件:<input type="file" name="upload" size="50" /><br />
选择第三个文件:<input type="file" name="upload" size="50" /><br />
<input type="submit" value="上传" />
</form>
Struts.xml:
<action name="multiFileUpload"
class="control.MultiFileUploadAction">
<param name="savePath">/upload</param>
<result name="success">/index.jsp</result>
</action>
MultiFileUploadAction.java:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class MultiFileUploadAction extends ActionSupport {
private static final int BUFFER_SIZE=16*1024;
//用File数组来封装多个上传文件域对象
private File[] upload;
//用String数组来封装多个上传文件名
private String[] uploadFileName;
//用String数组来封装多个上传文件类型
private String[] uploadContentType;
//保存文件的目录路径(通过依赖注入)
private String savePath;
public String execute() {
File[] srcFiles=this.getUpload();
//处理每个要上传的文件
for(int i=0;i<srcFiles.length;i++){
//根据服务器的文件保存地址和原文件名创建目录文件全路径
String dstPath=ServletActionContext.getServletContext().getRealPath(this.getSavePath())+"\\"+this.getUploadFileName()[i];
File dstFile=new File(dstPath);
this.copy(srcFiles[i], dstFile);
}
return SUCCESS;
}
//自己封装的一个把源文件对象复制成目标文件对象
private static void copy(File src,File dst){
InputStream in=null;
OutputStream out=null;
try{
in=new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
out=new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
byte[] buffer=new byte[BUFFER_SIZE];
int len=0;
while((len=in.read(buffer))>0){
out.write(buffer,0, len);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(null!=in){
try {
in.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(null!=out){
try {
out.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
}