You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot抛出MaxUploadSizeExceededException时CORS响应头缺失问题求助

Spring Boot抛出MaxUploadSizeExceededException时CORS响应头缺失问题求助

大家好,我最近在用Spring Boot开发一个支持文件上传的REST服务,通过Multipart POST请求来上传文件,但遇到了一个奇怪的CORS问题,想请教一下各位大佬。

先说说我的配置和实现:

  1. 文件上传大小限制配置(application.yml):
spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 1MB
      max-request-size: 1MB
  1. CORS与安全配置:
    我通过SecurityConfig配置了CORS策略,允许开发环境下React客户端(localhost:3000)的请求,同时配置了OAuth2资源服务器等安全规则:
@EnableWebSecurity
@EnableMethodSecurity
@Configuration
public class SecurityConfig implements WebMvcConfigurer {

    @Value("${security.cors-origin:}")
    private String allowedOrigin;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtDecoder decoder, HandlerMappingIntrospector introspector) throws Exception {
        return http
                .csrf(httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.disable())
                .authorizeHttpRequests(authCustomizer -> authCustomizer.requestMatchers(new MvcRequestMatcher(introspector, "/actuator/**")).permitAll())
                .authorizeHttpRequests(authCustomizer -> authCustomizer.requestMatchers(new MvcRequestMatcher(introspector, "/integration/**")).permitAll())
                .authorizeHttpRequests(authCustomizer -> authCustomizer.anyRequest().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(decoder)))
                .sessionManagement(sessionCustomizer -> sessionCustomizer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .build();
    }

    /**
     * Add a specified host to the allowed origin for Cross-Origin Resource Sharing
     *
     * This is needed in development as the origin of the front-end (localhost:3000)
     * is different to the origin of the back-end (localhost:8080)
     *
     * @param registry the CorsRegistry to use to add the allowed origin
     */
    @Override
    @ConditionalOnProperty(prefix = "security", name="cors-origin")
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(allowedOrigin)
                .allowCredentials(true)
        ;
    }
}
  1. 全局异常处理:
    我用@RestControllerAdvice实现了全局异常处理器,专门处理MaxUploadSizeExceededException,返回自定义的错误响应:
@RestControllerAdvice
@Slf4j
public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({ MaxUploadSizeExceededException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public FileUploadErrorMessage handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex, WebRequest request) {
        FileUploadErrorMessage errorMessage = new FileUploadErrorMessage("inputValidation", "invalid file");
        ValidationResult validationResult = new ValidationResult("invalid.logo.size");
        errorMessage.setErrors(new ArrayList<>(Collections.singleton(validationResult)));
        return  errorMessage;
    }
}

问题现象

当上传的文件超过大小限制,Spring抛出MaxUploadSizeExceededException时,我的自定义异常处理器返回的响应没有带上Access-Control-Allow-Origin头,导致前端跨域报错。

但奇怪的是:如果我不在全局异常处理器中处理这个异常,Spring会返回一个500 Internal Error的响应,这个响应里是有CORS头的!

我本来以为是因为这个异常是在请求到达控制器之前就被框架拦截抛出的,所以没走CORS处理流程,但后面这个现象又让我困惑了。

有没有大佬能解释一下这个奇怪的行为,并且告诉我该怎么修复,让自定义处理这个异常时也能带上正确的CORS响应头?

备注:内容来源于stack exchange,提问作者dascolagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 13:08:06