上传文件示例代码:
@ApiOperation("上传文件")
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ApiResult<String> uploadFile(@RequestPart("file") MultipartFile file) {
//调用七牛云上传后返回图片地址
if (file == null || file.isEmpty()) {
return ApiResult.error("上传文件不能为空");
}
log.info("file size:{}",file.getSize());
String fileUrl = uploadService.uploadFile(file);
return ApiResult.success(fileUrl);
}
**
MultipartProperties
**
单次请求异常:(>10M)
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException: the request was rejected because its size (13490731) exceeds the configured maximum (10485760)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.handleParseFailure(StandardMultipartHttpServletRequest.java:122)
单个文件异常:(>1M)
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)
修改文件大小限制:
方式一: yml文件中进行配置
spring:
servlet:
multipart:
# -1 无限制
max-file-size: 10MB
# -1 无限制
max-request-size: 20MB
方式二: bean进行配置
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(DataSize.of(10, DataUnit.MEGABYTES));
factory.setMaxRequestSize(DataSize.of(20, DataUnit.MEGABYTES));
return factory.createMultipartConfig();
}