0

I want to download a few photos by URL using Webflux and AsynchronousFileChannel, and all files are created but empty.

Here is my code:

public void downloadFilesFromUrl() throws IOException {
    List<Photo> notDownloadedFiles = //get photos with name and URL;
    for (Photo photo : notDownloadedFiles) {
        Path path = Paths.get(pathToFiles + File.separator + photo.getPhotoName());
        WebClient client = WebClient.builder().baseUrl(photo.getLoadSource()).build();
        Flux<DataBuffer> dataBufferFlux = client
                .get().accept(MediaType.APPLICATION_OCTET_STREAM)
                .retrieve()
                .bodyToFlux(DataBuffer.class);
        saveFileOnComputer(path, dataBufferFlux);
    }
}

private void saveFileOnComputer(Path path, Flux<DataBuffer> dataBufferFlux) throws IOException {
    AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, CREATE, WRITE);
    DataBufferUtils.write(dataBufferFlux, asynchronousFileChannel)
            .doOnNext(DataBufferUtils.releaseConsumer())
            .doAfterTerminate(() -> {
                try {
                    asynchronousFileChannel.close();
                } catch (IOException ignored) { }
            }).then();
}

If I try to use

DataBufferUtils.write(dataBufferFlux, path, StandardOpenOption.CREATE).block();

instead of calling saveFileOnServer(..) method, everything is fine. But I want to use exactly AsynchronousFileChannel.

izzager
  • 11
  • 5

1 Answers1

1

Okay, I think I fixed it.

private void saveFileOnServer(Path path, Flux<DataBuffer> dataBufferFlux) throws IOException {
    AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, CREATE, WRITE);
    DataBufferUtils.write(dataBufferFlux, asynchronousFileChannel).subscribe();
}

The official documentation says "Note that the writing process does not start until the returned Flux is subscribed to".

izzager
  • 11
  • 5