struts在web应用中上载文件

canca canca
2009-01-07 13:31
2
0

    在把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/

发表评论