首页 > 技术文章 > spring 基于multipart 文件上传

liuyonglin 2017-02-22 16:44 原文

一、使用MultipartFile上传,需要jar包

  1. 第一个需要使用 Apache 的 commons-fileupload 等 jar 包支持,但它能在比较旧的 servlet 版本中使用。

    在版本控制工具中加入

    /*文件上传下载*/
    "commons-fileupload:commons-fileupload:1.3.1"

   在spring-mvc.xml中配置bean

    <!--文件上传  MultipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <property name="defaultEncoding" value="UTF-8"/>
     <property name="maxUploadSize" value="5000000"/>
     <property name="maxInMemorySize" value="5000000"></property>
    </bean>
  其中属性详解:
    defaultEncoding="UTF-8" 是请求的编码格式,默认为iso-8859-1
    maxUploadSize="5400000" 是上传文件的大小,单位为字节
    uploadTempDir="fileUpload/temp" 为上传文件的临时路径
  2.定义一个上传文件的工具方法
    private boolean savefile(MultipartFile file){
     try {
     //文件保存
     //request.getSession().getServletContext().getRealPath("/"):获取Tomcat的路径
     String path =request.getServletContext().getRealPath("/")+"assets/"+file.getOriginalFilename();

     System.out.println("------------------------------"+path);
     //文件转存
     file.transferTo(new File(path));
     return true;
     } catch (IOException e) {
     e.printStackTrace();
     }
     return false;
    }
  3.上传一个文件

      

      

   4.上传多个文件

      

      

 

   注意:要在form标签中加上enctype="multipart/form-data"表示该表单是要处理文件的,这是最基本的东西,很多人会忘记然而当上传出错后则去找程序的错误,却忘了这一点

二、不需要jar包

  1.在spring-mvc中配置

    <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>

  2.web.xml中配置

  <!--Multipart文件上传-->
    <multipart-config>
     <!--上传文件的最大限制,5M=1204*1024*5-->
     <max-file-size>5242880</max-file-size>
     <!--一次表单提交中文件的大小限制-->
     <max-request-size>10485760</max-request-size>
     <!-- 多大的文件会被自动保存到硬盘上。0 代表所有 -->
     <file-size-threshold>0</file-size-threshold>
    </multipart-config>
三、两种方法的缺点与优势
   第一种:需要jar包
   第二种:不需要jar包,但是只兼容server3.0以上

推荐阅读