使用struts的标签库:
<body>
<s:form action="/uploadList.action" enctype="multipart/form-data" method="post">
<s:textfield label="文件名称" name="name"></s:textfield>
<s:file label="选择文件" name="upload"></s:file>
<s:file label="选择文件" name="upload"></s:file>
<s:file label="选择文件" name="upload"></s:file>
<s:submit value="上传"/>
</s:form>
</body>
记得加标签:
<%@ taglib uri="/struts-tags" prefix="s"%>
struts的配置文件:
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.multipart.maxSize" value="409715200" />
<package name="struct2" extends="struts-default">
<action name="uploadList" class="struct2.uploadFile">
<result>../success.jsp</result>
<result name="input">../tagUpload.jsp</result>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/bmp,image/x-png,image/gif</param>
<param name="maximumSize">4M</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
</package>
</struts>
<constant name="struts.multipart.maxSize" value="409715200" /> //修改默认的最大上传文件的限度
<pre name="code" class="html"><param name="maximumSize">4M</param>//限定文件大小,大小不大于上面的
action的处理过程:
package struct2;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class uploadFile extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
private List<File> upload;//文件集合
private List<String> uploadContextType;//文件类型集合
private List<String> uploadFileName;//上传文件的名称
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<File> getUpload() {
return upload;
}
public void setUpload(List<File> upload) {
this.upload = upload;
}
public List<String> getUploadContextType() {
return uploadContextType;
}
public void setUploadContextType(List<String> uploadContextType) {
this.uploadContextType = uploadContextType;
}
public List<String> getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String execute(){
String path = ServletActionContext.getServletContext().getRealPath("/WEB-INF/uploadList");
File file = new File(path);
if(!file.exists()){
file.mkdirs();//不存在时创建,养成好的习惯,每次检验文件呀是否存在(即使你已经创建)
}
for(int i=0;i<upload.size();i++){
try {
FileUtils.copyFile(upload.get(i), new File(file,uploadFileName.get(i)));
return SUCCESS;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}