今天在做项目学习的过程中,需要用到文件上传,启动项目正常,访问上传post请求突然报出了一个异常,特此记录一下。
1、控制台异常
org.springframework.web.multipart.maxuploadsizeexceededexception: maximum upload size exceeded; nested exception is java.lang.illegalstateexception: org.apache.tomcat.util.http.fileupload.fileuploadbase$filesizelimitexceededexception: the field file exceeds its maximum permitted size of 1048576 bytes. at org.springframework.web.multipart.support.standardmultiparthttpservletrequest.handleparsefailure(standardmultiparthttpservletrequest.java:121) at org.springframework.web.multipart.support.standardmultiparthttpservletrequest.parserequest(standardmultiparthttpservletrequest.java:114)
从上述异常可以看出,是因为上传的file文件超过了spring默认配置的最大值1048576 bytes,上传文件我们通常情况下是使用multipartfile接口类接收前端上传的文件,可见对于multipartfile文件的默认限制也是1048576 bytes,即1m。
但是很多情况下我们用手机直接拍摄的证件照或者是文档问阿金基本都是在2m以上,很显然这不能满足我们的日常需求,所以我们就要修改默认配置参数大小。
2、上传文件默认参数
springboot不同的版本,对应的设置参数不同:
spring boot 1.3.x and earlier
- multipart.maxfilesize
- multipart.maxrequestsize
spring boot 1.4.x and 1.5.x
- spring.http.multipart.maxfilesize
- spring.http.multipart.maxrequestsize
spring boot 2.x
- spring.servlet.multipart.maxfilesize
- spring.servlet.multipart.maxrequestsize
3、解决方法
3.1、方法1(在配置文件.yml或者.properties中直接修改参数)
例如我使用的是springboot 2.1.3的版本,然后直接再配置文件中设置参数大小:
#做限制的参数配置 spring: servlet: multipart: enabled: true #默认支持文件上传 max-file-size: 20mb # 最大支持文件大小 max-request-size: 30mb # 最大支持请求大小 #不做限制的参数配置 spring: servlet: multipart: enabled: true #默认支持文件上传 max-file-size: -1 #不做限制 max-request-size: -1 #不做限制
设置完重启项目即可成功上传文件。
3.2、方法2(自定义config配置类)
将参数配置在远程配置文件中心,如果是配置项目中的配置文件中,那就跟方法1一样了,就没必要再单独写配置类了,将参数配置在远程配置中心,就是为了可以根据临时需求动态修改参数,而不用重启项目。
常见的远程配置文件中心服务有nacos、apollo(阿波罗)、springcloud等等,我使用的是nacos配置中心服务:
自定义multipartfileconfig配置类:
import org.springframework.beans.factory.annotation.value; 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; /** * @author: 一宿君 * @date: 2022-03-23 19:18:51 * @description: */ @configuration public class multipartfileconfig { @value("${config.multifile.maxfilesize}") private long maxfilesize; @value("${config.multifile.maxrequestsize}") private long maxrequestsize; @bean public multipartconfigelement multipartconfigelement() { multipartconfigfactory factory = new multipartconfigfactory(); /** * 单个数据大小, * datasize.ofmegabytes(maxfilesize)默认是配置字节,将字节转化为mb */ factory.setmaxfilesize(datasize.ofmegabytes(maxfilesize)); // 总上传数据大小 factory.setmaxrequestsize(datasize.ofmegabytes(maxrequestsize)); return factory.createmultipartconfig(); } }
这样就可以随时控制上传文件的大小了!
总结
到此这篇关于springboot上传文件大小受限问题解决的文章就介绍到这了,更多相关springboot上传文件大小受限内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!