6

In my project , there is a need to download file from external service and store it in some path. So I was using RestTemplate in spring to download file as Byte[] . But then this operation is costing me memory consumption. I found out in this blog https://inneka.com/programming/spring/spring-webclient-how-to-stream-large-byte-to-file/ about using spring webClient and writing file to path . Since my concerned file is audio file im using APPLICATION_OCTET_STREAM . The problem the below code is not working . Im very new to reactive programming, any hints for this would be helpful.

public Mono<void> testWebClientStreaming(String filename, String format) throws IOException {
  WebClient webClient = WebClient.create("https://stackoverflow.com");
  String username = "Username";
  String token = "Password";
  String path = DOWNLOAD_TEMP_PATH + PATH_SEPERATOR + filename +"."+ format;

  Flux<DataBuffer> stream = webClient
      .get()
      .uri("/files/{filename}.{format}",
            filename, format)
      .accept(MediaType.APPLICATION_OCTET_STREAM)
      .header("Authorization", "Basic " + Base64Utils.encodeToString((username + ":" + token).getBytes(UTF_8)))
      .retrieve()
      .bodyToFlux(DataBuffer.class);

   return DataBufferUtils.write(stream, asynchronousFileChannel)
      .doOnComplete(() -> System.out.println("\n\n\n\n\n\n FINISHED  "))
      .doOnNext(DataBufferUtils.releaseConsumer())
      .doAfterTerminate(() -> {
          try {
                asynchronousFileChannel.close();
            } catch (IOException ignored) { }
       }).then();
}

I've tried exchange() , instead of retrive() which was working , but again I can't write the content in files . Or is there any way to achieve the same using other ways ?

shashantrika
  • 1,039
  • 1
  • 9
  • 29
  • what do you mean by "not working"? Files aren't written at all? Are you getting exceptions? Please provide more details about what's happening and what you're expecting. – Brian Clozel Dec 09 '19 at 19:52

0 Answers0