Unable to upload file due to Content-Type "multipart/form-data" not set for request body of type StandardMultipartFile

Viewed 2338

I have a remote service A which does the file upload. I have service B which calls the upload API of service A through FeignClient to upload a file

The method definition in Service A is something like

    ResponseEntity<?> upload(@RequestPart("file") MultipartFile file) { }

And the method in Service B is

    @FeignClient(url = "http://localhost:5000/")
    public interface uploadService {

    @RequestMapping(method = RequestMethod.POST, value = "/serviceA/upload")
    @Headers("Content-Type: multipart/form-data")
    void uploadFile(@RequestPart("file") MultipartFile file);
}

I am getting the error Content-Type "multipart/form-data" not set for request body of type StandardMultipartFile

I have tried most of the suggestions on https://github.com/spring-cloud/spring-cloud-netflix/issues/867 and https://github.com/OpenFeign/feign-form but nothing works for me

2 Answers

I was able to solve this issue by simply adding consumes = "multipart/form-data" in the RequestMapping. The reason was that I was mixing spring based annotations with open feign annotations. @Headers("Content-Type: multipart/form-data") works with Open feign. Here I am using spring-cloud-openfeign which provides abstraction to Open feign and make it easy to integration with spring framework components.

    @FeignClient(url = "http://localhost:5000/")
    public interface uploadService {

    @RequestMapping(method = RequestMethod.POST, value = "/serviceA/upload" consumes = "multipart/form-data" )
     void uploadFile(@RequestPart("file") MultipartFile file);
    }

If you have trouble just within the test just use org.springframework.mock.web.MockMultipartFile where you can set contentType as one of argument in construtor.

Related