本文介绍了如何将下载的文件作为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? 
}

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

推荐答案

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

  1. 实例化一个File对象(可能使用fileIddestination),这也是您想要的返回值
  2. File对象创建OutputStreamPathChannel对象
  3. 调用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();

这篇关于如何将下载的文件作为DataBuffer返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 05:24