How to Prepare a multipart body of a response in Spring Boot

How to Prepare a multipart body of a response in Spring Boot
Photo by Solen Feyissa / Unsplash

use PartEvent for Reactive Stack

To stream multipart data sequentially, you can provide multipart content through PartEvent objects.
Form fields can be created via FormPartEvent::create.
File uploads can be created via FilePartEvent::create.
You can concatenate the streams returned from methods via Flux::concat, and create a request for the WebClient.
For instance, this sample will POST a multipart form containing a form field and a file.
return Flux.concat(
            FormPartEvent.create("field", "field value"),
            FilePartEvent.create("file", resource)

PS: FormPartEvent are only available since Spring-Web version 6.0.

use MultiValueMap<String, HttpEntity> for Serverlet Stack

MultiValueMap<String, HttpEntity<?>> mixParts = new LinkedMultiValueMap<>();
        HttpHeaders jsonHeaders = new HttpHeaders();
        try {
            mixParts.add("metadata", new HttpEntity<>(objectMapper.writeValueAsString(response), jsonHeaders));
        } catch (JsonProcessingException e) {
            log.error("Oops!", e);
        HttpHeaders pdfHeaders = new HttpHeaders();
        mixParts.add("pdf", new HttpEntity<>(new ClassPathResource("contract_unsigned.pdf"), pdfHeaders));
        return new ResponseEntity<>(mixParts, HttpStatus.OK);


PartEvent (Spring Framework 6.0.5 API)
declaration: package: org.springframework.http.codec.multipart, interface: PartEvent