【文件属性】:
文件名称:Struts2上传文件出错
文件大小:870B
文件格式:XML
更新时间:2015-12-06 09:22:55
java struts2
<!-- 系统常量定义,定义上传文件字符集编码 -->
<!-- 系统常量定义,定义上传文件临时存放路径 -->
<!-- Action所在包定义 -->
<!-- Action名字,类以及导航页面定义 -->
<!-- 通过Action类处理才导航的的Action定义 -->
/upload.jsp
/input.jsp
package com.aptech.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
// 上传文件存放路径
private final static String UPLOADDIR = "/upload";
// 上传文件集合
private List file;
// 上传文件名集合
private List fileFileName;
// 上传文件内容类型集合
private List fileContentType;
public List getFile() {
return file;
}
public void setFile(List file) {
this.file = file;
}
public List getFileFileName() {
return fileFileName;
}
public void setFileFileName(List fileFileName) {
this.fileFileName = fileFileName;
}
public List getFileContentType() {
return fileContentType;
}
public void setFileContentType(List fileContentType) {
this.fileContentType = fileContentType;
}
public String execute() throws Exception {
for (int i = 0; i < file.size(); i++) {
// 循环上传每个文件
uploadFile(i);
}
return "input";
}
// 执行上传功能
private void uploadFile(int i) throws FileNotFoundException, IOException {
try {
InputStream in = new FileInputStream(file.get(i));
String dir = ServletActionContext.getRequest().getRealPath(
UPLOADDIR);
File uploadFile = new File(dir, this.getFileFileName().get(i));
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}