springboot文件上传出错, 文件超出限制: The field file exceeds its maximum permitted size of 1048576 bytes

springboot文件上传出错

  • 一、问题
  • 二、解决
    • 2.1 方式一(失败)
    • 2.1 方式二(成功)

一、问题

参考文章:
https://juejin.cn/post/7005448590990524430
https://stackoverflow.com/questions/37540028/how-to-set-the-max-size-of-upload-file

使用springboot上传文件时,出现以下错误

org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
        at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.handleParseFailure(StandardMultipartHttpServletRequest.java:124) ~[spring-web-5.3.29.jar!/:5.3.29]
        at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:115) ~[spring-web-5.3.29.jar!/:5.3.29]
        at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.3.29.jar!/:5.3.29]
        at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:122) ~[spring-web-5.3.29.jar!/:5.3.29]
        at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1210) ~[spring-webmvc-5.3.29.jar!/:5.3.29]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1044) ~[spring-webmvc-5.3.29.jar!/:5.3.29]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:965) ~[spring-webmvc-5.3.29.jar!/:5.3.29]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.3.29.jar!/:5.3.29]
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) [spring-webmvc-5.3.29.jar!/:5.3.29]

由日志信息得知,文件大小超过了限制,因为Spring boot内置的Tomcat默认支持单个文件最大1Mb

二、解决

需要设置将上传文件的大小限制修改。

2.1 方式一(失败)

项目springboot版本是2.0以上,修改yml文件,新增内容:

spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 5MB 
      max-request-size: 5MB

修改完之后测试,文件上传依然报错

2.1 方式二(成功)

新增一个配置类FileConfig

@Configuration
public class FileConfig {

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(DataSize.ofMegabytes(5)); //5MB
        factory.setMaxRequestSize(DataSize.ofMegabytes(5));
        return factory.createMultipartConfig();
    }
}

修改完之后, 文件上传成功

你可能感兴趣的:(SpringBoot,spring,boot,后端,java,tomcat)