1. @Controller
  2. public class FormTestController {
  3. /*
  4. * 假设表单有四项
  5. * 邮箱, 用户名
  6. * 头像(单文件)
  7. * 相册(多文件)
  8. * MultipartFile会自动封装文件
  9. * */
  10. @PostMapping
  11. public String upload(@RequestParam("email") String email,
  12. @RequestParam("username") String username,
  13. @RequestPart("headerImg") MultipartFile headerImg,
  14. @RequestPart("photos") MultipartFile[] photos) throws IOException {
  15. if(!headerImg.isEmpty()){
  16. // 文件非空, 保存到服务器
  17. String originalFilename = headerImg.getOriginalFilename();
  18. headerImg.transferTo(new File("D:\\" + originalFilename));
  19. }
  20. if(photos.length > 0){
  21. for(MultipartFile photo : photos){
  22. if(!photo.isEmpty()){
  23. String originalFilename = photo.getOriginalFilename();
  24. photo.transferTo(new File("H:\\cache" + originalFilename));
  25. }
  26. }
  27. }
  28. return "main";
  29. }
  30. }

文件大小限制


相关配置在MultipartAutoConfiguration里
multipartProperties
image.png
最大单文件是1mb, 最大总文件是10mb
修改: spring.servlet.mulitpart
application.yaml
image.png