Feign multipart with Json request part
Asked Answered
T

4

10

I have Feign client in one service with a method

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
 MyDto uploadDocument(@RequestPart("file") MultipartFile file,
                               @RequestPart("myDto") String myDto);

I have a controller in another service

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MyDto> uploadDocument(@RequestParam("file") MultipartFile file,
                                                      @RequestPart("myDto") MyDto myDto) {
.... some code here
    }

The issue I faced is that Feign sends myDto with Content-type : text/plain and I have HttpMediaTypeNotSupportedException

Is it possible to send @RequestPart("myDto") String myDto with Content-type : application/json ?

expected Raw request:

----------------------------boundary
Content-Disposition: form-data; name="file"; filename="fileName"
<file>
----------------------------boundary
Content-Disposition: form-data; name="myDto"
**Content-Type: application/json**
{"myDto": ""}

Current raw request:

----------------------------boundary
Content-Disposition: form-data; name="file"; filename="fileName"
<file>
----------------------------boundary
Content-Disposition: form-data; name="myDto"
**Content-Type: text/plain**
{"myDto": ""}
Travelled answered 24/7, 2020 at 9:20 Comment(4)
Can you change type of myDto in your Feign client from String to MyDto?Auk
It does not work, in this case I receive MissingServletRequestPartExceptionTravelled
Maybe this issue will help. You need to use feign-formAuk
Thanks, but they use String in controller. My goal is to use MyDto objectTravelled
C
10

Managed to solve this by replacing the feign-form PojoWriter. By default it's serializing each field of an object as a separate part.

    @Bean
    public Encoder feignEncoder () {
        return new MyFormEncoder(objectMapper, new SpringEncoder(messageConverters));
    }
public class MyFormEncoder extends SpringFormEncoder {
    /**
     * Constructor with specified delegate encoder.
     *
     * @param delegate  delegate encoder, if this encoder couldn't encode object.
     */
    public MyFormEncoder(ObjectMapper objectMapper, Encoder delegate) {
        super(delegate);

        val processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
        processor.addFirstWriter(new MyPojoWriter(objectMapper));
    }
}
@FieldDefaults(level = PRIVATE, makeFinal = true)
public class MyPojoWriter extends AbstractWriter {

    private ObjectMapper objectMapper;

    public MyPojoWriter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean isApplicable(Object object) {
        return isUserPojo(object);
    }

    @Override
    protected void write(Output output, String key, Object value) throws EncodeException {
        var data = "";
        try {
            data = objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
        }
        val string = new StringBuilder()
                .append("Content-Disposition: form-data; name=\"").append(key).append('"').append(CRLF)
                .append("Content-Type: application/json; charset=").append(output.getCharset().name()).append(CRLF)
                .append(CRLF)
                .append(data)
                .toString();

        output.write(string);
    }

    private boolean isUserPojo(@NonNull Object object) {
        val type = object.getClass();
        val typePackage = type.getPackage();
        return typePackage != null && typePackage.getName().startsWith("com.my-package.");
    }
}
Creatine answered 18/8, 2020 at 1:4 Comment(0)
I
6

Update to 2021.

//spring-cloud-openfeign-core
import org.springframework.cloud.openfeign.support.JsonFormWriter;


@Import(JsonFormWriter.class)
public class MyConfig {

@Bean
Encoder feignEncoder(JsonFormWriter jsonFormWriter) {
    return new SpringFormEncoder() {{
            var processor = (MultipartFormContentProcessor) getContentProcessor(ContentType.MULTIPART);
            processor.addFirstWriter(jsonFormWriter);
            processor.addFirstWriter(new SpringSingleMultipartFileWriter());
            processor.addFirstWriter(new SpringManyMultipartFilesWriter());
        }};
Ingenerate answered 25/8, 2021 at 14:17 Comment(0)
H
6

You need to define bean JsonFormWriter in your feign client's configuration.

Here is an example of the client:

@FeignClient(
        name = "my-client",
        configuration = MyClientConfiguration.class
)
public interface MyClient {

    @PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    void uploadFile(@RequestPart("request") MyFileUploadRequest request,
                                        @RequestPart("file") MultipartFile file);

}

public class MyClientConfiguration {

    @Bean
    JsonFormWriter jsonFormWriter() {
        return new JsonFormWriter();
    }
}

And an example of the controller:

@RestController
public class FileUploadApi {

    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void uploadFile(
            @RequestPart("request") MyFileUploadRequest request,
            @RequestPart("file") MultipartFile file) {
    }

This feature was added in scope of this PR: https://github.com/spring-cloud/spring-cloud-openfeign/pull/314

Hightail answered 6/9, 2022 at 17:41 Comment(0)
M
0

Using the @PathVariable annotation and with a registered SpringFormEncoder you need to convert the "myDto" into a MultipartFile.

The client:

@PostMapping(value = "/files/upload", consumes = MULTIPART_FORM_DATA_VALUE)
MyDto uploadDocument(@PathVariable("file") MultipartFile file, @PathVariable("myDto") MultipartFile myDto)

The encoder:

@RequiredArgsConstructor
public class FeignClientConfiguration {

    private final ObjectFactory<HttpMessageConverters> messageConverters;

    //To support multipart file upload
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }    

}

Creating MultipartFile from the DTO:

 public MultipartFile createMultipartFile(@NotNull MyDto myDto) throws JsonProcessingException {
        return new org.springframework.mock.web.MockMultipartFile(
                "fileName",
                "originalFileName",
                MediaType.APPLICATION_JSON.toString(),
                objectMapper.writeValueAsBytes(myDto));
    }

Why this solution with @PathVariable works is described here https://github.com/spring-cloud/spring-cloud-netflix/issues/867

Mena answered 16/5, 2022 at 15:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.