zoukankan      html  css  js  c++  java
  • 巧妙使用spring对commons fileUpload的包装

    巧妙使用spring对commons fileUpload的包装

             以前简单使用过spring的文件上传,当时没深入研究,以为spring只能实现单个文件的上传,所以后来就又大致学了下commons fileupload组件。在最近的工作中,有同事提出,他在把commons fileupload组件集成到spring中时总是出错,然后我大致看了一下,发现是spring DispatcherServlet的缘故。然后google了一下,发现sping本身就包装了commons fileupload,并且很好用。汗颜!为自己以前无知的写那篇《利用Jakarta commons fileupload组件实现多文件上传》汗颜!唉,都是自己以前不读书不看报的结果啊,呵呵:)

    一.前台页面        

             我们的目标是要实现多文件上传,并且预先我并不知道客户要上传多少个文件。我们先写个jsp页面吧,要实现可以动态控制上传多少文件,基本代码如下:

            <form method="post" action="./upload.do" enctype="multipart/form-data">
                
    <div id="uploadDiv">
                    
    <input type="file" name="file1" />
                
    </div>
                
    <input type="button" value="继续上传" onclick="javascript:btn_click();">
                
    <input type="hidden" id="fileCount" name="fileCount" value="1">
                
    <input type="submit" value="上传" />
            
    </form>

    恩,要实现动态控制上传文件个数,我们需要使用伟大的javascript了

     function btn_click(){
      
    var fileNo=Number(document.getElementById('fileCount').value)+1;
      newDiv
    =document.createElement("div")
      newDiv.id
    ="divFile"+fileNo;
      document.getElementById(
    'uploadDiv').appendChild(newDiv)
      document.getElementById(
    'fileCount').value=fileNo;
      newDiv.innerHTML
    ="<input type='file' name='file"+fileNo+"'>";
     }

    ok,现在我们的界面如下:http://dl2.csdn.net/down4/20070710/10163733412.JPG

    二.后台实现    

      1. 好了,前台我们搞定了,现在考虑一下后台处理吧。我写了一个Command Bean,非常简单,如下:

    public class FUploadBean {
     
    private byte[] file;
     
    public byte[] getFile() {
      
    return file;
     }

     
    public void setFile(byte[] file) {
      
    this.file = file;
     }

    }

     在spring Web MVC模式中,必须定义一个Command对象,将其和Form表单绑定。这个command class需要在spring上下文中进行配置,可以作为controller的property进行配置。呆会会在配置文件中看到相关配置。

    2. 然后就是一个Controller

    public class FUploadController extends SimpleFormController {

     
    public ModelAndView onSubmit(HttpServletRequest request,
       HttpServletResponse res, Object obj, BindException errors)
       
    throws Exception {

      MultipartHttpServletRequest multipartRequest 
    = (MultipartHttpServletRequest) request;

      
    int fileCount = Integer.parseInt(request.getParameter("fileCount"));

      
    for (int i = 1; i <= fileCount; i++{
       CommonsMultipartFile cFile 
    = (CommonsMultipartFile) multipartRequest.getFile("file" + i);
       File uploadedFile 
    = new File("E:/upload" + "/"+ cFile.getOriginalFilename());
       FileCopyUtils.copy(cFile.getBytes(), uploadedFile);
      }


      
    return null;
     }


     
    // 注册一个spring的编辑器非常重要,没有这个方法,上传将不能进行
     protected void initBinder(HttpServletRequest request,
       ServletRequestDataBinder binder) 
    throws ServletException {
      binder.registerCustomEditor(
    byte[].class,
        
    new ByteArrayMultipartFileEditor());
     }

    }

    注意:必须定义initBinder方法。

    三.配置文件

    接下来就是配置文件了,熟悉spring的人应该很容易看懂了。

    1.web.xml

        <servlet>
            
    <servlet-name>springStudy</servlet-name>
            
    <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            
    </servlet-class>
            
    <load-on-startup>1</load-on-startup>
        
    </servlet>
        
    <servlet-mapping>
            
    <servlet-name>springStudy</servlet-name>
            
    <url-pattern>*.do</url-pattern>
        
    </servlet-mapping>

    2.springStudy-servlet.xml

        <bean id="multipartResolver"
            class
    ="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            
    <property name="maxUploadSize" value="50000000" />
            
    <property name="defaultEncoding" value="utf-8" />
        
    </bean>

        
    <bean id="urlMapping"
            class
    ="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
            
    <property name="mappings">
                
    <props>
                    
    <prop key="/upload.do">uploadServlet</prop>
                
    </props>
            
    </property>
        
    </bean>
        
    <bean id="uploadServlet"
            class
    ="chb.spring.study.web.FUploadController">
            
    <property name="commandClass"
                value
    ="chb.spring.study.web.FUploadBean" />
        
    </bean>

    注:需要注意的是,在spring中要实现文件上传,必须在spring的上下文中定义MultipartResolver,这样spring在发现该表单请求是mutipart时,就会使用spring定义的解析器去解析。这里我们使用的是
    CommonsMultipartResolver,也就是会转化为commons fileupload。CommonsMultipartResolver继承自CommonsFileUploadSupport,而CommonsFileUploadSupport是对commons fileupload组件的包装,所以我们可以在定义multipartResolver时设置相关参数,比如最大允许上传文件数,字符编码等。这里设置<property name="defaultEncoding" value="utf-8" />就是为了解决中文问题。

  • 相关阅读:
    DB2使用MERGE INTO语句实现西虹市首富的新增及更新操作
    [转]如何更换 Ubuntu 18.04 LTS 的 GDM 登录界面背景
    ubuntu18.04安装flat-remix-gnome主题
    DB2中ALTER TABLE的使用
    《MySQL必知必会》学习笔记——附录B 样例表
    《MySQL必知必会》学习笔记——附录A MySQL入门
    《MySQL必知必会》学习笔记——第1章 了解SQL
    使用Spring Boot接受HTTP GET/POST请求的一个SQL并返回结果
    查看linux目录剩余空间大小
    ETCD数据空间压缩清理
  • 原文地址:https://www.cnblogs.com/hehe520/p/6330232.html
Copyright © 2011-2022 走看看