struts多文件上传
1、文件载入页面
<body>
<form method="post" enctype="multipart/form-data" action="file_load">
文件一:<input type="file" name="images"><br/>
文件二:<input type="file" name="images"><br/>
文件三:<input type="file" name="images"><br/>
<input type="submit" value="提交"/>
</form>
</body>
2、struts.xml里面action配置
<struts> <package name="default" namespace="/" extends="struts-default" > <action name="file_*" class="com.edu.hpu.action.FileAction" method="{1}"> <result>/file_{1}.jsp</result> </action> </package> </struts>
3、FileAction
package com.edu.hpu.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileAction extends ActionSupport {
/**
* 使用数组进行多文件接收
* images:接收到的文件
* imagesFileName:接收到的文件名
*/
private File[] images;
private String[] imagesFileName;
public File[] getImages() {
return images;
}
public void setImages(File[] images) {
this.images = images;
}
public String[] getImagesFileName() {
return imagesFileName;
}
public void setImagesFileName(String[] imagesFileName) {
this.imagesFileName = imagesFileName;
}
@Override
public String execute() throws Exception {
return super.execute();
}
public String input() throws Exception {
return SUCCESS;
}
public String load() throws Exception {
//获得并创建存储路径
String savePath = ServletActionContext.getServletContext().getRealPath("/images");
File filePath = new File(savePath);
if(!filePath.exists()) {
filePath.mkdirs();
}
//遍历获得文件进行文件存储
for(int i = 0; i < images.length; i++) {
File file = new File(filePath,imagesFileName[i]);
if(!file.exists()) {
file.createNewFile();
}
System.out.println(file.getAbsolutePath());
FileUtils.copyFile(images[i], file);
}
return SUCCESS;
}
}
4、结果展示页面
<body>
文件
<s:iterator value="imagesFileName" var="fileName">
<s:property value="fileName"/>,
</s:iterator>上传成功!
</body>