Spingboot CORS error only for Multipart POST

2019-03-04 22:18发布

Hello am facing a peculiar issue

I have enabled CORS on my Springboot API Server with following configuration

@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

All my POST requests are working except an API for image upload. Its implemented as

@PostMapping(value = "/profiles/{id}/image")
@ResponseStatus(value = HttpStatus.CREATED)
public void uploadProfileImage(@PathVariable Long id, @RequestPart MultipartFile file) {
    this.userService.uploadProfileImage(id, file);
}

On browser I see the OPTION for this request succeeding but the actual POST being made but hanging out and the console the displaying this error.

Options call on console

The error is

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:10000/users/profiles/1/image. (Reason: CORS request did not succeed).[Learn More]

The API does works correctly when used from PostMan so I think the issue is with CORS configuration and not actual API logic

Any pointers? Have tried adding @CrossOrigin to controller and specific API without any success.

2条回答
做个烂人
2楼-- · 2019-03-04 23:01

Add this bean in your configuration to support CORS:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("Access- Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
    configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
查看更多
Melony?
3楼-- · 2019-03-04 23:08

I found the issue. I am using angular 7 and angular http component. Had to change my post method from

uploadImageFile(file: File, id: number) {
        const formData: FormData = new FormData();
        formData.append('file', file, file.name);
        return this.http.post(`${environment.apiEndpoint}/users/profiles/${id}/image`, formData);
    }

to

uploadImageFile(file: File, id: number) {
        const formData: FormData = new FormData();
        formData.append('file', file, file.name);
        return this.http.post(`${environment.apiEndpoint}/users/profiles/${id}/image`, formData, {
            // This is required to manage post multipart updates
            headers: {}
        });
    }
查看更多
登录 后发表回答