Home > database >  How to return File downloaded as DataBuffer
How to return File downloaded as DataBuffer

Time:10-19

I am downloading a file like below:

private File downloadAndReturnFile(String fileId, String destination) {
    log.info("Downloading file.. "   fileId);
    Path path = Paths.get(destination);
    Flux<DataBuffer> dataBuffer = webClient.get().uri("/the/download/uri/"   fileId   "").retrieve()
            .bodyToFlux(DataBuffer.class)
            .doOnComplete(() -> log.info("{}", fileId   " - File downloaded successfully"));
    
    //DataBufferUtils.write(dataBuffer, path, StandardOpenOption.CREATE).share().block();
    
    return ???? // What should I do here to return above DataBuffer as file? 
}

How can I return the dataBuffer as a File? Or, how can I convert this dataBuffer to a File object?

CodePudding user response:

You could use DataBufferUtils.write method. To do that, you should

  1. instantiate a File object (maybe using fileId and destination) which is also the return value you want
  2. create OutputStream or Path or Channels object from the File object
  3. call DataBufferUtils.write(dataBuffer, ....).share().block() to write the DataBuffer into the file

viz. (all thrown exceptions are omitted),

...
File file = new File(destination, fileId);
Path path = file.toPath();
DataBufferUtils.write(dataBuffer, path, StandardOpenOption.CREATE).share().block();
return file;

Or,

...
Path path = Paths.get(destination);
DataBufferUtils.write(dataBuffer, path, StandardOpenOption.CREATE).share().block();
return path.toFile();

CodePudding user response:

In case someone looking for a full code. Just sharing Tonny's solution to the fullest.

private File downloadAndReturnFile(String fileId, String destination) throws FileNotFoundException {
            log.info("Downloading file.. "   fileId);
            Flux<DataBuffer> dataBuffer = webClient.get().uri("/the/download/uri/"   fileId   "").retrieve()
                    .bodyToFlux(DataBuffer.class)
                    .doOnComplete(() -> log.info("{}", fileId   " - File downloaded successfully"));
            Path path = Paths.get(destination);
            DataBufferUtils.write(dataBuffer, path, StandardOpenOption.CREATE).share().block();
            return path.toFile();
        }
  • Related