这是一个上传文件的jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>上传页面</title> </head> <body> <form action="${pageContext.request.contextPath }/UploadAction.do" method="post" enctype="multipart/form-data"> 上传用户:<input name="username" type="text"/><br/> 上传文件1:<input name="list[0]" type="file"><br/> 上传文件2:<input name="list[1]" type="file"><br/> <input type="submit" value="提交"> </form> </body> </html>
package cn.lfd.web.formbean; import java.util.ArrayList; import java.util.List; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; public class UploadFileBean extends ActionForm { private String username; private List<FormFile> list = new ArrayList<FormFile>();//用来保存多文件的List集合 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public FormFile getList(int index) { return list.get(index); } public void setList(int index, FormFile formfile) { list.add(formfile); } public List<FormFile> getAll() { return this.list; } }
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="UploadFileBean" type="cn.lfd.web.formbean.UploadFileBean"></form-bean> </form-beans> <span style="white-space:pre"> </span><action-mappings> <action path="/UploadFileUI" forward="/WEB-INF/jsp/upload.jsp"></action> <action path="/UploadAction" type="cn.lfd.web.action.UploadAction" name="UploadFileBean" validate="false" scope="request" ></action> <span style="white-space:pre"> </span></action-mappings> </struts-config>
package cn.lfd.web.action; import java.io.FileOutputStream; import java.io.InputStream; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; import cn.lfd.web.formbean.UploadFileBean; /* * 处理上传请求的action */ public class UploadAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileBean bean = (UploadFileBean) form; //取出bean中封装文件的list集合 List<FormFile> list = bean.getAll(); //取出list中的每一个FormFile对象,再利用传统的IO流方式进行文件的copy for(int i=0;i<list.size();i++) { FormFile formfile = list.get(i); InputStream in = formfile.getInputStream(); //new出一个输出流把文件数据写到d盘 FileOutputStream out = new FileOutputStream("d:\\"+formfile.getFileName()); byte[] buff = new byte[1024]; int len = 0; while(-1!=(len=in.read(buff))) { out.write(buff, 0, len); } in.close(); out.close(); } return null; } }最后文件就会成功上传到我的d盘