struts文件上传(上传文件大小设置、验证文件大小)

    技术2025-01-19  5

    一、web.xml配置,这里将文件上传配置为upload模块。

    <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <display-name>Struts Blank Application</display-name> <!-- Standard Action Servlet Configuration (with debugging) --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>config/upload</param-name> <param-value>/WEB-INF/upload/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>2</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <!-- Standard Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- The Usual Welcome File List --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>/tags/struts-bean</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> <taglib> <taglib-uri>/tags/struts-html</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> <taglib> <taglib-uri>/tags/struts-logic</taglib-uri> <taglib-location>/WEB-INF/struts-logic.tld</taglib-location> </taglib> <taglib> <taglib-uri>/tags/struts-nested</taglib-uri> <taglib-location>/WEB-INF/struts-nested.tld</taglib-location> </taglib> <taglib> <taglib-uri>/tags/struts-tiles</taglib-uri> <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location> </taglib> </web-app>

     

    二、struts-config.xml配置和资源文件 <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="uploadForm" type="org.apache.struts.webapp.upload.UpLoadForm" /> </form-beans> <action-mappings> <action path="/upload" forward="/selfile.jsp" /> <!-- Upload Action --> <action path="/uploadsAction" type="org.apache.struts.webapp.upload.UpLoadAction" name="uploadForm" scope="request" input="input"> <forward name="input" path="/selfile.jsp" /> <forward name="display" path="/display.jsp" /> </action> </action-mappings> <!-- 这里设置上传文件的最大值。 -1 不限制大小。缺省值:-1 --> <controller maxFileSize="2M" inputForward="true" /> <message-resources parameter="org.apache.struts.webapp.upload.UploadResources"/> </struts-config>

    资源文件:UploadResources_zh_CN.properties maxLengthExceeded=已经超过了上传文件所允许的最大值。 maxLengthExplanation=注意:这个应用程序允许上传文件的最大值是2M。请看"/WEB-INF/upload/struts-config.xml" 文件更改这个值。

     

    三、选择上传文件页面:selfile.jsp,如此访问此页面: <html:link module="/upload" page="/upload.do"> 继续上传</html:link></h2> <%@ page contentType="text/html; charset=GBK" %> <%@ page import="org.apache.struts.action.*, java.util.Iterator, org.apache.struts.Globals" %> <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <logic:messagesPresent> <ul> <html:messages id="error"> <li><bean:write name="error"/></li> </html:messages> </ul><hr /> </logic:messagesPresent> <html:html> <html:form action="uploadsAction.do" enctype="multipart/form-data"> <html:file property="theFile"/> <html:submit/> </html:form>

     

    四、表单bean:   UpLoadForm.java package org.apache.struts.webapp.upload; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.*; import org.apache.struts.upload.*; /** * <p>Title:UpLoadForm</p> * <p>Description: QRRSMMS </p> * <p>Copyright: Copyright (c) 2004 jiahansoft</p> * <p>Company: jiahansoft</p> * @author wanghw * @version 1.0 */ public class UpLoadForm extends ActionForm { public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded"; protected FormFile theFile; public FormFile getTheFile() { return theFile; } public void setTheFile(FormFile theFile) { this.theFile = theFile; } public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = null; //has the maximum length been exceeded? Boolean maxLengthExceeded = (Boolean) request.getAttribute( MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED); if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) { errors = new ActionErrors(); errors.add( ActionMessages.GLOBAL_MESSAGE , new ActionMessage("maxLengthExceeded")); errors.add( ActionMessages.GLOBAL_MESSAGE , new ActionMessage("maxLengthExplanation")); } return errors; } }

     

    五、处理上传的文件:UpLoadAction.java package org.apache.struts.webapp.upload; import java.io.*; import javax.servlet.http.*; import org.apache.struts.action.*; import org.apache.struts.upload.FormFile; /** * <p>Title:UpLoadAction</p> * <p>Description: QRRSMMS </p> * <p>Copyright: Copyright (c) 2004 jiahansoft</p> * <p>Company: jiahansoft</p> * @author wanghw * @version 1.0 */ public class UpLoadAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (form instanceof UpLoadForm) {//如果form是UpLoadsForm String encoding = request.getCharacterEncoding(); if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) { response.setContentType("text/html; charset=gb2312"); } UpLoadForm theForm = (UpLoadForm ) form; FormFile file = theForm.getTheFile();//取得上传的文件 String contentType = file.getContentType(); String size = (file.getFileSize() + " bytes");//文件大小 String fileName= file.getFileName();//文件名 try { InputStream stream = file.getInputStream();//把文件读入 String filePath = request.getRealPath("/");//取当前系统路径 ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream bos = new FileOutputStream(filePath + "/" + file.getFileName()); //建立一个上传文件的输出流,将上传文件存入web应用的根目录。 //System.out.println(filePath+"/"+file.getFileName()); int bytesRead = 0; byte[] buffer = new byte[8192]; while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead);//将文件写入服务器 } bos.close(); stream.close(); }catch(Exception e){ System.err.print(e); } //request.setAttribute("dat",file.getFileName()); request.setAttribute("contentType", contentType); request.setAttribute("size", size); request.setAttribute("fileName", fileName); return mapping.findForward("display"); } return null; } }

     

    五、成功页display.jsp <%@ page contentType="text/html; charset=GBK" %> <%@ page import="org.apache.struts.action.*, java.util.Iterator, org.apache.struts.Globals" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> 上传成功!上传信息如下: <p> <b>The File name:</b> <%= request.getAttribute("fileName") %> </p> <p> <b>The File content type:</b> <%= request.getAttribute("contentType") %> </p> <p> <b>The File size:</b> <%= request.getAttribute("size") %> </p> <hr /> <hr /> <html:link module="/upload" page="/upload.do"> 继续上传</html:link></h2>

     

    六、测试 从本站下载整个目录结构TestStruts并放入tomcat的webapps目录下,在浏览器中输入: http://127.0.0.1:8080/TestStruts/upload/upload.do

     

    最新回复(0)