Spring WebClient: How to stream large byte[] to file?

后端 未结 4 927
天命终不由人
天命终不由人 2021-02-02 17:11

It seems like it the Spring RestTemplate isn\'t able to stream a response directly to file without buffering it all in memory. What is the proper to achieve this us

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 17:31

    With recent stable Spring WebFlux (5.2.4.RELEASE as of writing):

    final WebClient client = WebClient.create("https://example.com");
    final Flux dataBufferFlux = client.get()
            .accept(MediaType.TEXT_HTML)
            .retrieve()
            .bodyToFlux(DataBuffer.class); // the magic happens here
    
    final Path path = FileSystems.getDefault().getPath("target/example.html");
    DataBufferUtils
            .write(dataBufferFlux, path, CREATE_NEW)
            .block(); // only block here if the rest of your code is synchronous
    
    

    For me the non-obvious part was the bodyToFlux(DataBuffer.class), as it is currently mentioned within a generic section about streaming of Spring's documentation, there is no direct reference to it in the WebClient section.

提交回复
热议问题