【问题标题】:Spring WebFlux: How to return a file as byte array from DBSpring WebFlux:如何从数据库中将文件作为字节数组返回
【发布时间】:2020-08-30 07:24:53
【问题描述】:

刚开始学习 Spring Reactive,我找不到任何关于如何做这么简单的事情的例子。如果没有 WebFlux,我的控制器看起来像这样:

@GetMapping("/retrieveAttachment/{id}")
public ResponseEntity<byte[]> downloadFile(@PathVariable String id) throws Exception {
    Attachment attachment = documentManagerService.getAttachment(id);

    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + attachment.getFileName() + "\"")
            .body(attachment.getFileAttachment().getData());
}

现在使用 WebFlux,我的 documenManagerService 返回 Mono&lt;Attachment&gt;,这就是我想出的:

public Mono<ServerResponse> getAttachment(ServerRequest request) {
    Mono<byte[]> mono = documentManagerService.getAttachment(request.pathVariable("id"))
            .map(attachment -> attachment.getFileAttachment().getData());
    return ServerResponse
            .ok()
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM.toString())
            .body(mono, byte[].class);
}

我可以下载文件,但问题是文件没有扩展名 因为我没有设置 Content Disposition Header。如何在不进行阻塞调用的情况下进行设置?

【问题讨论】:

    标签: java arrays file spring-webflux


    【解决方案1】:

    也许通过使用flatMap。我是在手机上写的,所以没有尝试过或仔细检查过任何东西。

    public Mono<ServerResponse> getAttachment(ServerRequest request) {
        return documentManagerService.getAttachment(request.pathVariable("id"))
            .flatMap(attachment -> {
                return ServerResponse.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM.toString())
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + attachment.getFileName() + "\"")
                    .bodyValue(attachment.getFileAttachment().getData())
            });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 2013-01-16
      • 2020-09-08
      相关资源
      最近更新 更多