当前位置:首页 > JavaServer Page > 正文内容

struts在web应用中上载文件

canca17年前 (2009-01-07)JavaServer Page431
commons fileupload 是Apache commons项目的一部分,FileUpload 使你很容易在servlet及web 应用中提供一个鲁棒的、高性能的文件上特性。FileUpload按照RFC 1867 ( "Form-based File Upload in HTML")处理HTTP请求。即,如果HTTP request 以 POST方法提交,并且content type 设置为"multipart/form-data",那么FileUpload可以处理该请求,在web应用中提供文件上载的功能。其使用方法见commons fileupload的相关文档。

    在把FileUpload与struts结合(jsp + uploadactiono)使用过程中发现,如果在action mapping配置中不指定formbean,文件上传过程正常。如果指定了formbean,文件上传不正常,取不到文件。以下是几个文件片断:

upload.jsp
<table>
<form action="uploadaction.do?method=uploadByFileUpload" method="post" enctype="multipart/form-data" >
<tr >
    <td width="150" align="right">需上载的文件:</td>
    <td><input type="file" name="uploadfile" ></td>
</tr>

<tr>
    <td height="22" align="right">&nbsp;</td>
    <td align="left"> <input type="submit" value="提交" class="button"></td>
</tr>
</form>
</table>

UploadAction.java
    public ActionForward uploadByFileUpload(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response)
                                   throws Exception {
        ......

String dir="....";
        DiskFileUpload fu= new DiskFileUpload();

        fu.setSizeMax( UPLOAD_MAXSIZE);
        fu.setSizeThreshold( MAX_DATA_IN_MEM);
        fu.setRepositoryPath( System.getProperty("java.io.tmpdir"));
       
        try {
            List fileItem= fu.parseRequest( request);
            Iterator it= fileItem.iterator();
            while( it.hasNext()){
                FileItem item= (FileItem)it.next();
                if( !item.isFormField() && null!= item.getName() &&
                    0!= item.getName().trim().length()){
                    String clientPath = item.getName();
                    String fileName = new File(clientPath).getName();
                   
                    File destDir = new File( dir);
                   
                    File file = new File(destDir, fileName);
                    item.write( file);
                    map.put( item.getFieldName(),
                             dir+ File.separator+ fileName);
                }
            }
        } catch (Exception e) {
            String str= "文件上载异常,错误信息:"+ e.getMessage();
            System.out.println(str);
             throw new Exception( str, e);
        }

       ......
    }

struts-config.xml

    <action path="/uploadaction"
            name="TestForm"         <!--指定formbean-->
     type="UploadAction"
     parameter="method" >
     <forward name="success" path="/success.jsp" />
</action>

现象:在struts-config.xml文件中,如果指定了formbean——name="TestForm" ,则文件无法正确上传,UploadAction中的fu.parseRequest( request)方法返回值为null;如果去掉了说明formbean的name属性,则文件可以正常上传。

原因:struts的RequestProccessor.process已经包含了处理文件上传的方法。如果在action配置中设置了formbean ,那么在你自己的action处理request之前,struts已经在RequestProccessor.populate方法中处理了request,因此,在自己的action中就取不到上传的文件了。

处理:如果要自己在action中处理文件上传工作,那么就不要在配置文件中配置formbean。

其他选择:如果仍需使用formbean,那么可以使用struts内置的文件上传功能。具体使用方法见struts的相关文档,以及struts的upload例子。以下是几个文件片断:

upload.jsp
基本同上,修改form标签的action属性
<form action="uploadaction.do?method=uploadByStruts" method="post" enctype="multipart/form-data" >

UploadAction.java
    public ActionForward uploadByStruts(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response)
                                   throws Exception {
        ActionErrors errs= new ActionErrors();
       
        if (form != null){
            DynaActionForm theForm = (DynaActionForm)form;
           FormFile file = (FormFile)theForm.get("uploadfile");
            try{
                String fileName= file.getFileName();
                if ("".equals(fileName)) {return null;}
                InputStream stream = file.getInputStream();
                OutputStream bos = new FileOutputStream("D:/"+fileName);
                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 (FileNotFoundException fnfe) {
   ...
            }catch (IOException ioe) {
   ...
            }catch (NullPointerException e){
                ...   
            }
           
        }else{
               ...
        }
       
        if (!errs.isEmpty()){
          saveErrors( request, errs);
        }

       return mapping.findForward( "success");

    }

struts-config.xml
    <form-bean name="TestForm" type="org.apache.struts.action.DynaActionForm">
      <form-property name="uploadfile" type="org.apache.struts.upload.FormFile" />
    </form-bean>

    <action path="/uploadaction"
            name="TestForm"         <!--指定formbean-->
     type="UploadAction"
     parameter="method" >
     <forward name="success" path="/success.jsp" />
</action>

    <controller maxFileSize="2M" />

//<controller maxFileSize="2M" tempDir="d:/temp" inputForward="true"/>临时目录

注意,使用struts自带的文件上传功能,最带文件尺寸限制用<controller maxFileSize="2M" />来配置。另为struts对文件上载功能提供了两种处理实现:org.apache.struts.upload.CommonsMultipartRequestHandler 和 org.apache.struts.upload.DiskMultipartRequestHandler。struts默认的是前者,如果要使用后者,需在<controller>中配置,配置样例如下<controller maxFileSize="2M" multipartClass="org.apache.struts.upload.DiskMultipartRequestHandler" />。而且,DiskMultipartRequestHandler是使用commons uploadload实现的。


更多信息请参见以下网址:
http://jakarta.apache.org/commons/fileupload/
http://struts.apache.org/

扫描二维码推送至手机访问。

版权声明:本文由Ant.Master's Blog发布,如需转载请注明出处。

本文链接:https://iant.work/post/341.html

标签: JavaServer Page
分享给朋友:

“struts在web应用中上载文件” 的相关文章

JBoss,Tomcat 中文URL支持方法

JBOSS 找到jboss4的deploy\jbossweb-tomcat50.sar\server.xml,编辑该文件,在下面的XML节点中增加红色的字<Connector port="8080" address="${jboss.bind.address}"  &nbs...

在web.xml不认<taglib>解决办法

在web.xml不认<taglib>解决办法: 如果是头是这样的<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application&n...

struts,ajax乱码解决方案

乱码问题好像跟我们中国程序员特别有缘,一直困扰着我们,从开始的JSP乱码问题,STRUTS乱码问题,到现在的AJAX乱码问题,无一不是搞得许多程序员焦头烂额的,整天骂XXX产品对中文支持不了,UTF-8无法使用中文啊什么的,其实这里面被骂的产品中其实99%以上是对中文支持非常好的,而出现乱码的原...

JSP动态include与静态include的区别

动态INCLUDE   jsp:include page="included.jsp" flush="true" />它总是会检查所含文件中的变化,适合用于包含动态页面,并且可以带参数。静态INCLUDE   用include伪码实现,定不会检...

浏览网页时的错误代号

① 客户方错误    100  继续    101  交换协议  ② 成功    200  OK    201  已创建 &nbs...

FCKeditor的秘密

       哈哈。。由于项目的需要,这几天一直在搞FCKeditor。其实,FCKeditor配置很简单。但不知道怎么样。在我的项目里FCKeditor总不能在FireFox里显示。开始我还以为是我的配置有问题。但我从头到尾检查了配置文件...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。