首页 > 代码库 > 【springmvc】springmvc中如何上传文件

【springmvc】springmvc中如何上传文件

 

使用到的组件:可自行根据情况选择版本

<!--上传依赖包-->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.2</version>
            </dependency>
            <!--commons-upload依赖包begin-->
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.5</version>
            </dependency>
            <!--commons-upload依赖包END-->

xx-servlet.xml文件配置

 

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--默认编码为ISO-8859-1-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--上传大小限制为100MB,maxUploadSize配置的是字节数-->
        <property name="maxUploadSize" value="104857600"/>
        <!--Set the maximum allowed size (in bytes) before uploads are refused-->
        <property name="maxInMemorySize" value="40960"/>
        <!--uploadTempDir上传文件的临时路径,文件上传完后,临时目录中的临时文件会被自动清除-->
        <property name="uploadTempDir" value="fileUpload/temp"/>
    </bean>

 

tips:关于uploadTempDir,需要创建WEB-INF/fileUpload/temp这两个文件夹;因为程序不会自动创建,如果不创建,会直接报错;至于叫什么,层级如何,根据自己情况可修改;

maxUploadSize:配置的是字节数;
maxInMemorySize:Set the maximum allowed size (in bytes) before uploads are refused

 

如果在上传过程中,乱码,可以在web.xml中配置如下filter,指定编码格式为utf-8;

    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--支持异步-->
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

 

前端HTML:

如果想一次选择多文件上传,可以设置 multiple;  一次上传一个文件的话,不设置这个属性;

另外,enctype="multipart/form-data" 是必须设置的;

<form name="Form2" action="/rest/upload/springUpload" method="post" enctype="multipart/form-data">
    <h1>使用spring mvc提供的类的方法上传文件</h1>
    <input type="file" name="file" multiple="multiple">
    <input type="submit" value="upload"/>
</form>

 

后台代码:

    /*
     *采用spring提供的上传文件的方法
     */
    @RequestMapping(value = "springUpload", method = RequestMethod.POST)
    public ModelAndView springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
        long startTime = System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMultipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator fileNames = multiRequest.getFileNames();

            // 上传文件夹是否存在,不存在创建;最终格式为/uploadFile/2017-06-01/{文件名}
            String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/") + DateTimeUtils.getNow().toString();
            File pathFile = new File(realPath);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }

            while (fileNames.hasNext()) {
                //一次遍历所有文件
                List<MultipartFile> fileList = multiRequest.getFiles(fileNames.next().toString());
                if (fileList != null) {
                    for (MultipartFile file : fileList) {
                        String path = realPath + "/" + file.getOriginalFilename();
                        System.out.println("上传路径:" + path);
                        //上传
                        file.transferTo(new File(path));
                    }
                }
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("运行时间:" + String.valueOf(endTime - startTime) + "ms");
        return new ModelAndView("fileupload/success");
    }

 

最终效果:

技术分享

技术分享

 

参考:

# 关于CommonsMultipartResolver配置

https://docs.spring.io/spring/docs/1.2.x/javadoc-api/org/springframework/web/multipart/commons/CommonsMultipartResolver.html

http://www.cnblogs.com/fjsnail/p/3491033.html # 有个问题,就是方法三种并没有解决一次上传多个资源时的情况;

 

【springmvc】springmvc中如何上传文件