Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 263|回复: 0

[struts学习]struts中的文件上传

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-11 00:57:47 | 显示全部楼层 |阅读模式
    这是学struts1.2.4自带的例子。所有文件及目录结构请在本站下载。

      

      
      
    一、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>
    </html:html>

    --------------------------------------------------------------------------------

    四、表单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



      
      
       
       

         
       

         
       
      



    源码下载:http://file.javaxxz.com/2014/10/11/005746437.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-26 13:42 , Processed in 0.345279 second(s), 37 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表