美文网首页
SpringBoot中使用 commons-fileupload

SpringBoot中使用 commons-fileupload

作者: 河里的枇杷树 | 来源:发表于2018-06-27 11:45 被阅读78次
    1. pom.xml中添加依赖
            <!-- 文件上传所依赖的jar包 -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
    
    1. application.properties中添加允许上传的最大值
    #上传文件最大值
    spring.servlet.multipart.max-file-size=100Mb  
    #单个请求的最大值
    spring.servlet.multipart.max-request-size=100Mb  
    
    1. 进行使用
        @RequestMapping("/doUpload")
        public String doUpload(HttpSession session, HttpServletRequest request) throws IOException {
            long startTime = System.currentTimeMillis();
    ​
            //获取存储app文件夹的路径
            String appPath = session.getServletContext().getRealPath("/app");
            File appRootDir = new File(appPath);
            if (!appRootDir.exists()) {
                System.out.println("存储app的文件夹不存在 appPath= " + appPath);
                appRootDir.mkdirs();
            } else {
                System.out.println("存储app的文件夹存在 appPath= " + appPath);
            }
    ​
    ​
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    ​
            if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    ​
                Iterator<String> names = multiRequest.getFileNames();
    ​
                while (names.hasNext()) {
                    MultipartFile file = multiRequest.getFile(names.next().toString());
                    if (file != null) {
                        File appFile = new File(appRootDir, file.getOriginalFilename());
                        file.transferTo(appFile);
                    }
                }
            }
    ​
            long endTime = System.currentTimeMillis();
            System.out.println("上传时间:" + String.valueOf(endTime - startTime) + "ms");
            return "home";
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot中使用 commons-fileupload

          本文链接:https://www.haomeiwen.com/subject/qtjbyftx.html