Issue
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?
Solution
You could use DataBufferUtils.write
method. To do that, you should
- instantiate a
File
object (maybe usingfileId
anddestination
) which is also the return value you want - create
OutputStream
orPath
orChannel
s object from theFile
object - call
DataBufferUtils.write(dataBuffer, ....).share().block()
to write theDataBuffer
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();
Answered By - Tonny Tc