项目场景:
SpringBoot 文件上传
问题描述
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:122) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:115) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:87) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1201) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1035) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) [spring-webmvc-5.3.7.jar:5.3.7]
原因分析:
从异常信息可以看出,最大上传大小溢出了,最大上传大小为:1048576 bytes
也就是 1M
。
从 SpringBoot 的自动配置类中可以找到关于文件上传的自动配置类:org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
:
...
@EnableConfigurationProperties(MultipartProperties.class)
public class MultipartAutoConfiguration {
...
}
可以看到这个配置类加载了属性配置类:MultipartProperties
:
@ConfigurationProperties(prefix = "spring.servlet.multipart", ignoreUnknownFields = false)
public class MultipartProperties {
/**
* Max file size.
*/
private DataSize maxFileSize = DataSize.ofMegabytes(1);
/**
* Max request size.
*/
private DataSize maxRequestSize = DataSize.ofMegabytes(10);
/**
* Threshold after which files are written to disk.
*/
private DataSize fileSizeThreshold = DataSize.ofBytes(0);
...
public DataSize getMaxFileSize() {
return this.maxFileSize;
}
public void setMaxFileSize(DataSize maxFileSize) {
this.maxFileSize = maxFileSize;
}
}
从源码中可以看到,如果我们没有设置最大文件大小 maxFileSize
的话,会给一个默认值,这个默认值就是 1048576 bytes
:
public static DataSize ofMegabytes(long megabytes) {
return new DataSize(Math.multiplyExact(megabytes, 1048576L));
}
解决方案:
默认的文件上传大小限制肯定不满足我们的生产需要,所以我们要设置上面 MultipartProperties
中的 maxFileSize
的值:
spring:
servlet:
multipart:
max-file-size: 50MB