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();
        jsonHeaders.setContentType(MediaType.APPLICATION_JSON);
        try {
            mixParts.add("metadata", new HttpEntity<>(objectMapper.writeValueAsString(response), jsonHeaders));
        } catch (JsonProcessingException e) {
            log.error("Oops!", e);
        }
        HttpHeaders pdfHeaders = new HttpHeaders();
        pdfHeaders.setContentType(MediaType.APPLICATION_PDF);
        mixParts.add("pdf", new HttpEntity<>(new ClassPathResource("contract_unsigned.pdf"), pdfHeaders));
        return new ResponseEntity<>(mixParts, HttpStatus.OK);

References

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

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe