首先你需要搭建一个struts1的完整开发环境,在lib目录下导入struts1的核心jar包
然后在WEB-INF目录下建立一个struts-config.xml 文件
<?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>
<%@ 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/> 上传文件:<input name="formfile" type="file"><br/> <input type="submit" value="提交"> </form> </body> </html>建立好一个formbean保存上传的文件和各个字段,struts1会自动把表单的数据封装到改formbean中
package cn.lfd.web.formbean; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; public class UploadFileBean extends ActionForm { private String username; private FormFile formfile; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public FormFile getFormfile() { return formfile; } public void setFormfile(FormFile formfile) { this.formfile = formfile; } }表单提交后跳转到一个UploadAction中进行处理,struts1会把表单数据封装到ActionForm中
package cn.lfd.web.action; import java.io.FileOutputStream; import java.io.InputStream; 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中封装的上传数据 FormFile formfile = bean.getFormfile(); 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; } }