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
- 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();
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();
}