首页 > 解决方案 > 使用 Webflux 下载文件并在浏览器中查看的更好方法

问题描述

我正在学习 WebFlux。我正在从如下所示的休息端点下载文件:

@RequestMapping(value = { "/downloadAlfFile/{id}" }, method = RequestMethod.GET)
    private static ResponseEntity<byte[]> getFileContent(@PathVariable String id) throws IOException {
        String uri = "http://localhost:8080/api/1/downloadcontent/" + id
                + "/getcontent";
        String fileName = getFileNameMethod(id); // filename here
        WebClient client = WebClient.builder().baseUrl(uri).build(); // the WebClient
        Flux<DataBuffer> dataBufferFlux = client.get().headers(headers -> headers.setBasicAuth("admin", "admin"))
                .accept(MediaType.APPLICATION_OCTET_STREAM).retrieve().bodyToFlux(DataBuffer.class); // dataBuffer
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachement; filename=\"" + fileName + "\"")
                .body(getInputStreamFromFluxDataBuffer(dataBufferFlux).readAllBytes());
    }
    
    

    public static InputStream getInputStreamFromFluxDataBuffer(Flux<DataBuffer> data) throws IOException {
        PipedOutputStream osPipe = new PipedOutputStream();
        PipedInputStream isPipe = new PipedInputStream(osPipe);

        DataBufferUtils.write(data, osPipe).subscribeOn(Schedulers.boundedElastic()).doOnComplete(() -> {
            try {
                osPipe.close();
            } catch (IOException ignored) {
            }
        }).subscribe(DataBufferUtils.releaseConsumer());
        return isPipe;
    }
  1. 问题1:有没有更好的方法来实现同样的目标?我正在寻求帮助,因为上面看起来像是补丁工作而不是干净的代码。
  2. 问题 2:如何在浏览器中打开 pdf/images 而不是使用 webflux 下载它们?我试过in-line而不是attachment但没有帮助。我应该怎么办?

标签: springspring-bootspring-webflux

解决方案


推荐阅读