SpringBoot中使用 commons-fileupload

2018-06-27  本文已影响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";
    }
}
上一篇下一篇

猜你喜欢

热点阅读