【问题标题】:How to return File downloaded as DataBuffer如何将下载的文件返回为 DataBuffer
【发布时间】:2021-12-05 13:38:56
【问题描述】:

我正在下载如下文件:

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 转换为 File 对象?

【问题讨论】:

    标签: spring spring-boot spring-webflux project-reactor


    【解决方案1】:

    如果有人在寻找完整的代码。只是充分分享 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();
            }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 能否请您输入伪代码?对不起,我很笨。
      • 您介意提供destination 变量的真实值和下载uri 路径吗?我可以使用代码下载到文件。
      • 这是我的目的地(字符串)-c:/aap/test01.pdf。我的原始问题的注释行写入文件没有任何问题。
      • 要从Path 对象中检索File 对象,您可以简单地使用Path.toFile() 方法。如果您的原始代码成功将内容写入文件,您可以return path.toFile();。不好意思我不在windows环境,所以不确定是否要创建File对象windows环境和linux不一样。
      • 啊……我的错。我创建了该方法的副本,但仍在调用错误的方法。它按预期工作。可以说足够感谢@Tonny。带着灿烂的笑容接受它。 !
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2011-01-30
      • 1970-01-01
      • 2013-09-02
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多