26 Aralık 2022 Pazartesi

SpringWebFlux DefaultPartHttpMessageReader Sınıfı

Giriş
multipart/form-data cevapları okuyabilmemizi sağlar. Açıklaması şöyle
It reads the "multipart/form-data" requests to a stream of Parts
content metodu
Örnek
Şöyle yaparız. Burada block() metodu kullanıldığı için setStreaming(false) yapılıyor
final var partReader = new DefaultPartHttpMessageReader();
partReader.setStreaming(false); 

WebClient webClient = WebClient.builder().build();
ResponseEntity<Flux<Part>> request = webClient
  .get()
  .uri("...")
  .accept(MediaType.MULTIPART_MIXED)
  .retrieve()
  .toEntityFlux((inputMessage, context) ->
    partReader
      .read(ResolvableType.forType(byte[].class), inputMessage, Map.of()))
  .block();

byte[] image = null;
    
List<Part> parts = request.getBody().collectList().block();

for (Part part : parts) {
  // access individual parts here
  System.out.println(part.headers());
  if (part.headers().get("Content-Type").get(0).equals("image/jpeg")) {
    image = DataBufferUtils.join(part.content())
      .map(dataBuffer -> {
        byte[] bytes = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(bytes);
        DataBufferUtils.release(dataBuffer);
        return bytes;
      }).block();
  }
}

return image;
Açıklaması şöyle
part.headers() will give you the headers and part.content() will give you the actual content in DataBuffer format.

We iterate the list of parts, and determine which one is an image by peeking into the headers. Once we get that, we use the DataBufferUtils , a helper class to convert the buffer into byte array format.

And that’s it, extracting images/files from multipart data is now a walk in the park thanks to Spring Flux !

Hiç yorum yok:

Yorum Gönder