如何 return 文件下载为 DataBuffer

How to return File downloaded as DataBuffer

我正在下载如下文件:

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? 
}

如何 return 将 dataBuffer 作为文件?或者,如何将此 dataBuffer 转换为 File 对象?

您可以使用 DataBufferUtils.write method。为此,您应该

  1. 实例化一个 File 对象(可能使用 fileIddestination)这也是你想要的 return 值
  2. File 对象
  3. 创建 OutputStreamPathChannels 对象
  4. 调用DataBufferUtils.write(dataBuffer, ....).share().block()DataBuffer写入文件

即。 (所有抛出的异常都省略),

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

或者,

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

以防有人寻找完整代码。完全分享 Tonny 的解决方案。

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