springboot返回文件
时间: 2023-10-21 15:11:28 浏览: 119
springboot文档
在Spring Boot中返回文件可以使用以下方法:
1. 使用ResponseEntity:
```java
@GetMapping("/download")
public ResponseEntity<ByteArrayResource> downloadFile() throws IOException {
// load file as ByteArrayResource
InputStream is = new FileInputStream(new File("path/to/file"));
byte[] data = IOUtils.toByteArray(is);
ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + "filename")
.contentLength(data.length)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
```
2. 使用StreamingResponseBody:
```java
@GetMapping("/download")
public StreamingResponseBody downloadFile(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + "filename");
InputStream is = new FileInputStream(new File("path/to/file"));
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
is.close();
};
}
```
其中,第一种方法使用了ResponseEntity来返回文件内容,并设置了响应头信息,第二种方法使用了StreamingResponseBody来实现文件的流式传输。
阅读全文