spring boot 如何将文件byte[]作为下载文件响应给接口调用
时间: 2023-12-20 16:07:08 浏览: 18
在 Spring Boot 中,你可以使用 `ResponseEntity` 来将文件的 `byte[]` 数组作为下载文件响应给接口调用。
首先,确保你的接口方法返回类型为 `ResponseEntity<byte[]>`。
然后,你可以使用以下代码示例来实现文件下载:
```java
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
// ...
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
// 从某处获取文件的 byte[] 数组
byte[] fileBytes = getFileBytes();
// 将文件字节数组包装为 ByteArrayResource 对象
ByteArrayResource resource = new ByteArrayResource(fileBytes);
// 设置响应头信息
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", "filename.txt");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 返回带有文件字节数组的 ResponseEntity
return ResponseEntity.ok()
.headers(headers)
.contentLength(fileBytes.length)
.body(fileBytes);
}
```
在上述示例中,`getFileBytes()` 方法用于获取文件的 `byte[]` 数组。你可以根据自己的需求从文件系统、数据库或其他来源获取该数组。
然后,通过创建 `ByteArrayResource` 对象,将 `byte[]` 数组包装为一个资源。
接下来,设置响应头信息,包括文件名和内容类型。
最后,通过返回一个带有文件字节数组的 `ResponseEntity` 对象,将文件作为下载文件响应给接口调用。