在Spring Boot中,您可以使用以下方法来下载文件:
- 使用
ResponseEntity<byte[]>
返回文件数据和相关的HTTP头信息。
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
// 从文件系统或其他来源获取文件
File file = new File("path/to/file");
// 将文件读入字节数组
byte[] fileContent = Files.readAllBytes(file.toPath());
// 设置HTTP头信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
// 返回ResponseEntity对象
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
}
- 使用
InputStreamResource
和ResponseEntity<InputStreamResource>
返回文件的输入流和相关的HTTP头信息。
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
// 从文件系统或其他来源获取文件
File file = new File("path/to/file");
// 创建文件输入流
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
// 设置HTTP头信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
// 返回ResponseEntity对象
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.body(resource);
}
这两种方法都可以用来下载文件,具体使用哪种方法取决于您的需求和偏好。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/853621.html