SpringBoot限制文件或图片上传大小的配置方法
问题
SpringBoot默认上传文件大小不能超过1MB,超过之后会报以下异常:
org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
Springboot内嵌的Tomcat限制了单个文件/图片只能是1MB的大小,超过了这个默认的大小就会抛出异常。
解决
方法一
在配置文件 (application.properties/application.yml) 中加入如下设置即可:
-
1.X版本的话
spring.http.multipart.max-file-size=10MB spring.http.multipart.max-request-size=20MB
-
2.X版本的话 注意,不配置 spring.servlet.multipart.enable,默认为true。
spring.servlet.multipart.max-file-size=10Mb spring.servlet.multipart.max-request-size=20Mb 或者使用 spring.servlet.multipart.maxFileSize=10MB spring.servlet.multipart.maxRequestSize=20MB
方法二
配置在启动类中:单位MB或者KB都可以:
springBoot 版本:2.4.8 对应的Spring-webmvc版本: 5.3.8
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import javax.servlet.MultipartConfigElement;
@Configuration
public class FileUploadConfig {
/**
* 配置上传文件大小的配置
* @return MultipartConfigElement
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件大小200mb
factory.setMaxFileSize(DataSize.ofMegabytes(200L));
//设置总上传数据大小10GB
factory.setMaxRequestSize(DataSize.ofGigabytes(10L));
return factory.createMultipartConfig();
}
}
官方介绍
Handling Multipart File Uploads Spring Boot embraces the Servlet 3 javax.servlet.http.Part API to support uploading files. By default, Spring Boot configures Spring MVC with a maximum size of 1MB per file and a maximum of 10MB of file data in a single request. You may override these values, the location to which intermediate data is stored (for example, to the /tmp directory), and the threshold past which data is flushed to disk by using the properties exposed in the MultipartProperties class. For example, if you want to specify that files be unlimited, set the spring.servlet.multipart.max-file-size property to -1.
The multipart support is helpful when you want to receive multipart encoded file data as a @RequestParam-annotated parameter of type MultipartFile in a Spring MVC controller handler method.
See the source for more details.
[Note] It is recommended to use the container’s built-in support for multipart uploads rather than introducing an additional dependency such as Apache Commons File Upload.
