如何在java spring boot中将字节数组作为内存文件返回?

the*_*mer 7 java arrays spring file spring-boot

我有一个字节数组作为数据。现在,如何使用 Spring Boot 编写一个控制器方法来将此字节数组作为文件返回?如果我用这个字节数组数据创建一个文件,那么我还应该删除它,对吗?

有没有办法将此字节数组作为文件发送,而不必在我的项目中物理创建文件,也许通过网络或其他方式发送所有字节?

但是,如果这是不可能的,那么创建文件、在 REST API 中响应然后删除它是解决这个问题的唯一方法吗?我的控制器方法在 Spring Boot 中看起来像这样

@GetMapping("/download")
public ResponseEntity<Resource> download(String param) throws IOException {
    // Assume I already have this byte array from db or something
    Byte[] a = getItFromDB();

    // return it as a file without explicitly creating another file in my machine
    // I am ok with changing return type of this method from ResponseEntity to anything else if you have a solution
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*sch 13

只需获取byte[]数组,将其包装到 a ByteArrayResource (这是接口的实现Resource)中,从中构建 a ResponseEntity<Resource>,然后返回它。

@GetMapping("/download")
public ResponseEntity<Resource> download(String param) throws IOException {
    // Assume I already have this byte array from db or something
    byte[] array = getItFromDB();

    ByteArrayResource resource = new ByteArrayResource(array);
    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .contentLength(resource.contentLength())
            .header(HttpHeaders.CONTENT_DISPOSITION,
                    ContentDisposition.attachment()
                        .filename("whatever")
                        .build().toString())
            .body(resource);
}
Run Code Online (Sandbox Code Playgroud)

无需创建临时文件,也无需更改返回类型。

标头中的媒体类型Content-Type和标头中的文件名Content-Disposition是接收下载的网络浏览器(或任何客户端)的重要提示。您可能应该使用比上面代码中的值更好的值。例如:对于 PNG 图像内容,您将使用 MediaType.IMAGE_PNG"whatever.png"。然后网络浏览器可能会打开系统最喜欢的图像查看器。