angular - 使用springboot和angular下载文件
问题描述
我使用角度和弹簧,我正在尝试下载文件。
我只能使用 spring('http://localhost:8080/download) 下载文件,但我不知道如何将它与 angular 连接。对于春天,我正在使用 ResponseEntitiy 这是代码
@GetMapping(value ="/download")
public ResponseEntity<Object> downloadFile() throws IOException, PropertyException, JAXBException
{
bookListService.convertBookListToXml();
return bookListService.downloadXml();
};
和服务
public ResponseEntity<Object> downloadXml() throws FileNotFoundException {
String filename = "booksExport.xml";
File file = new File(filename);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition",
String.format("attachment; filename=\"%s\"", file.getName()));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/txt")).body(resource);
return responseEntity;
}
我尝试了许多选项来将响应与角度联系起来,但没有一个有效。ResponseEntity 甚至是好的回报吗?
角度目前是
html
<button class="btn btn-primary" style="margin-left: 10px" (click)="downloadFile2()">download File</button>
组件.ts
downloadFile2() {
this.fileDownloadService.downloadFile3();
}
和服务
downloadFile3(): any {
return this.http.get('http://localhost:8080/download');
}
解决方案
对于 ResponseEntity,使用 InputStreamResource 类型,在头部添加信息并在正文中传递文件,如下所示:
public ResponseEntity<InputStreamResource> viewCheckExcel() throws JRException, IOException {
ByteArrayInputStream in = service.generateFile();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=customers.xlsx");
return ResponseEntity
.ok()
.headers(headers)
.body(new InputStreamResource(in));
}
这适用于文件 Excel,但结构相同。
要在服务中转换 ByteArrayInputStream 中的文件,您可以这样做:
File file = new File(wfc.getPathExcel()+"/customer.xlsx");
return new ByteArrayInputStream(Files.readAllBytes(file.toPath()));
注意:在 FrontEnd 的方法中指定接收的文件类型。
推荐阅读
- php - 提交后ajax不会刷新表单但会发布数据
- spring - 具有多个 Web 模块的 Spring 模块化
- html - 修复了使用弹性框的边聊菜单
- docker - 厨房创建错误:无法完成#create 操作:[work_image build failed: The command '/bin/sh -c yum install -y hostname iproute less lsof
- javascript - 手动添加到 HTML 范围输入会产生意想不到的结果
- twilio - Twilio Studio 创建变量
- r - 在R中用匹配替换字符串的问题
- php - laravel 中的短信
- amazon-cloudformation - Cloudformation 模板中 Parameter Store 中 EC2 实例类型的动态参考
- php - 每天在服务器上保存文件副本