设置临时目录

启动时,添加参数,注意,不要加空格!

  1. -Djava.io.tmpdir=./

默认的目录一旦被删除就会报错:

Failed to parse multipart servlet request; nested exception is java.io.IOExc

设置大小限制

默认1M

  1. spring:
  2. servlet:
  3. multipart:
  4. max-file-size: 100MB #单个数据的大小
  5. max-request-size: 100MB #总数据的大小

后台接收

controller接收

  1. @PostMapping("/upload")
  2. public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
  3. if (file.isEmpty()) {
  4. return Result.error("文件为空,添加失败");
  5. }
  6. labelTypeService.addFile(file);
  7. return Result.success("添加成功");
  8. }

保存文件

  1. # springboot获取项目根目录
  2. new ClassPathResource("").getFile().getAbsolutePath()
  3. # 保存。file必须为绝对路径,例如:
  4. FIle toFile = new File(new File(basePath).getAbsolutePath(),file.getOriginalFilename());
  5. file.transferTo(toFile)

readLines

  1. public static List<String> readLines(MultipartFile file) throws IOException {
  2. BufferedReader bf = new BufferedReader(new InputStreamReader(file.getInputStream()));
  3. String strTmp;
  4. ArrayList<String> list = new ArrayList<>();
  5. while ((strTmp = bf.readLine()) != null) {
  6. if (StringUtils.isNotBlank(strTmp)) {
  7. list.add(strTmp);
  8. }
  9. }
  10. return list;
  11. }