如何将下载得到的DataBuffer转换为File对象并返回
解决方案
你注释的DataBufferUtils.write就是Spring官方提供的将Flux<DataBuffer>写入本地文件的工具方法,直接启用该逻辑,写入完成后将Path转为File返回即可。
修正后的完整代码
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")) .doOnError(e -> log.error("{} - File download failed", fileId, e)); // 建议补充异常处理 // 写入文件到指定路径,share()用于允许多次订阅,block()会阻塞直到写入完成 DataBufferUtils.write(dataBuffer, path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING) .share() .block(); // 直接将Path转为File返回 return path.toFile(); }
注意事项
- 如果你是在响应式Web项目(如Spring WebFlux)中使用,不建议直接调用
block()阻塞线程,建议将方法返回值改为Mono<File>,去掉block()后用map转换返回值:private Mono<File> downloadAndReturnFile(String fileId, String destination) { Path path = Paths.get(destination); Flux<DataBuffer> dataBuffer = webClient.get().uri("/the/download/uri/" + fileId).retrieve() .bodyToFlux(DataBuffer.class) .doOnComplete(() -> log.info("{} - File downloaded successfully", fileId)); return DataBufferUtils.write(dataBuffer, path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING) .then(Mono.fromCallable(() -> path.toFile())); } DataBufferUtils.write会自动释放DataBuffer资源,不需要手动处理缓冲区释放- 建议补充目标路径的权限校验、目录不存在时的自动创建逻辑,避免写入失败
内容的提问来源于stack exchange,提问作者Ajay Kumar
相关产品推荐
相关产品推荐

