springboot

springboot上传文件大小受限制怎么解决

小亿
330
2023-08-09 23:50:49
栏目: 编程语言

默认情况下,Spring Boot 的文件上传大小受限制,可以通过以下几种方式解决:

  1. 修改 application.properties 文件:在 application.properties 文件中添加以下配置,设置最大文件上传大小。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
  1. 使用 application.yml 文件:在 application.yml 文件中添加以下配置,设置最大文件上传大小。
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
  1. 自定义配置类:创建一个配置类,继承 WebMvcConfigurerAdapter 并重写 configurePathMatch 方法。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setMaxUploadSize(10 * 1024 * 1024); // 设置最大文件上传大小为 10MB
}
}
  1. 使用 @ControllerAdvice 统一处理上传文件大小限制异常:创建一个全局异常处理类,使用 @ControllerAdvice 注解,然后在方法中处理 MaxUploadSizeExceededException 异常。
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public String handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
// 处理上传文件大小超出限制的异常
return "error";
}
}

这些方法可以根据具体情况选择使用,一般情况下,修改 application.properties 或 application.yml 文件即可满足需求。

0
看了该问题的人还看了