一、创建上传文件的页面,代码如下所示
1、Struts2也可以很方便地实现多文件上传。 在输入表单域增加多个文件域:multifileupload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>多文件上传</title>
</head>
<body>
<font color="red"><s:fielderror/></font>
<form action="multiFileUpload.action" method="POST" enctype="multipart/form-data">
文件标题:<input type="text" name="title" size="50" value="${param.title }"/><br/>
<!-- 设置二个文件域,名字相同 -->
选择第一个文件:<input type="file" name="upload" size="50"/><br/>
选择第二个文件:<input type="file" name="upload" size="50"/><br/>
<input type="submit" value=" 上传 "/>
</form>
</body>
</html>
2、在Action类中用数组来封装该多个文件域:MultiFileUploadAction.java
package org.qiujy.web.struts2;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
publicclass MultiFileUploadAction extends ActionSupport {
privatestaticfinalintBUFFER_SIZE = 16 * 1024;
// 文件标题
private String title;
// 用File数组来封装多个上传文件域对象
private File[] upload;
// 用String数组来封装多个上传文件名
private String[] uploadFileName;
// 用String数组来封装多个上传文件类型
private String[] uploadContentType;
// 保存文件的目录路径(通过依赖注入)
private String savePath;
//以下为所有属性的getter和setter。省略。。。
// 自己封装的一个把源文件对象复制成目标文件对象
privatestaticvoid 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 = newbyte[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 (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public String execute() throws Exception {
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);
}
returnSUCCESS;
}
}
3、在Struts.xml中配置只需要改变action的名称配置其余基本不需要改变什么