Action
package com.liu.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 javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUpAction extends ActionSupport{
private String username;//接收表单中用户名。
private File[] file;// 指定要接受的文件-->文件接收名:属性名必须和form表单中的name属性值相同。
private String[] fileFileName;//文件接收名-->固定写法:文件接收名+FileName;
private String[] fileContentType;// 获得上传文件的MIME类型-->固定写法:文件接收名+ContentType
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public File[] getFile() {
return file;
}
public void setFile(File[] file) {
this.file = file;
}
public String[] getFileFileName() {
return fileFileName;
}
public void setFileFileName(String[] fileFileName) {
this.fileFileName = fileFileName;
}
public String[] getFileContentType() {
return fileContentType;
}
public void setFileContentType(String[] fileContentType) {
this.fileContentType = fileContentType;
}
public String fileUpLoade() throws IOException {
//获得servletContent,sc在获得服务器的根路径
ServletContext sc = ServletActionContext.getServletContext();
for(int i=0; i<file.length;i++) {
String realPath = sc.getRealPath("/");
realPath = realPath+"uploads"+"/"+fileFileName[i];
FileUtils.copyFile(file[i], new File(realPath));
System.out.println(realPath);
}
return SUCCESS;
}
}
struts.xml
<packagename="up" namespace="/"extends="struts-default">
<actionname="uploade"class="com.liu.action.FileUpAction"method="fileUpLoade">
<resultname="success">/index.jsp</result>
<resultname="input">/fileUp.jsp</result>
</action>
</package>
jsp
<form action="${pageContext.request.contextPath}/uploade"method="post"enctype="multipart/form-data">
姓名:<inputtype="text"name="username"><br/>
文件:<inputtype="file"name="file"><br/>
文件2:<inputtype="file"name="file"><br/>
文件3:<inputtype="file"name="file"><br/>
<inputtype="submit"value="提交"><br/>
</form>