SpringBoot中使用|SpringBoot中使用 commons-fileupload 上传文件

  1. pom.xml中添加依赖
commons-fileupload commons-fileupload 1.3.1

  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 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"; } }

    推荐阅读