Springboot 文件上传超过限制处理

springboot文件上传报错

一、错误原因

springboot项目在上传较大文件时报错: 
Maximum upload size exceeded;org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.

报错的原因是:

2、在启动类上加上@CONFIGURATION注解,且在类中添加一下代码:

二、解决方法

知道了是tomcat的默认设置限制了上传的文件大小,那我们只需要改变默认设置即可。

1、在【APPLICATION.PROPERTIES】配置文件中加入如下代码:

  1.  
    # maxFileSize 单个数据大小
  2.  
    spring.servlet.multipart.maxFileSize = 10MB
  3.  
    # maxRequestSize 是总数据大小
  4.  
    spring.servlet.multipart.maxRequestSize=100MB

有两点要注意:

(1)这里“10MB”不能写成“10Mb”,否则会报另一个错,如下:

(2)SpringBoot的版本不同,这两个配置语句也不一样,具体版本对应如下:

  • Spring Boot 1.3 版本:

     multipart.maxFileSize

  • Spring Boot 1.4 版本和 1.5 版本:

     spring.http.multipart.maxFileSize

  • Spring Boot 2.0 版本:

     spring.servlet.multipart.maxFileSize

2、在配置类上加上@CONFIGURATION注解 配置Bean,且在类中添加一下代码:

/**
 * @Description:
 * @Auther: MingHao
 * @CreateDate: 14:13 2020-4-8
 * @Version: 1.0
 */
@Configuration
public class MultipartConfig {
    /**
     * 文件上传配置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个数据大小
        factory.setMaxFileSize("102400KB"); // KB,MB
        // 总上传数据大小
        factory.setMaxRequestSize("1024000KB");
        return factory.createMultipartConfig();
    }
}

3、如有网关,在网关中也加入如上配置(外面进不来,里面设置了也没用)

4.以上设置完以后,需要配置日志信息

  g4j:WARN No appenders could be found for logger (com.netease.qa.testng.TestngRetry).
  log4j:WARN Please initialize the log4j system properly.

文件的名称为  log4j.properties  , 文件中的内容设置为:

log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n



原文地址:https://www.cnblogs.com/mh-study/p/12660423.html