angular - 在 Angular 中下载具有原样文件名的 Excel 文件

标签 angular typescript

如何下​​载 Angular 应用程序中的服务返回的 Excel 文件?我正在使用file-saver库。这是我的代码:

let blob = new Blob([response],  {type: 'application/vnd.openxmlformat-officedocument.spreadsheetml.sheet;'});
saveAs(blob, 'hello.xlsx');

这是 Angular 服务的响应:

return this.http.get(`${this.reportsUrl}`, { responseType: 'blob'});

我的后端服务(Spring MVC)的响应。 excelCreatedResource 的类型为 org.springframework.core.io.Resource:

return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + excelCreateResource.getFilename() + "\"")
                .body(excelCreateResource);

我不想提供hello.xlsx。相反,我只想下载文件而不更改服务返回的文件名。如果我直接从浏览器访问该 URL,我就可以下载 Excel 文件。

最佳答案

根据您的问题,我认为您需要观察完整的响应并从中获取标题详细信息。在 Angular 中,你可以使用

来做到这一点
let observable$ = this.http.get(`${this.reportsUrl}`, { observe: 'response'});
observable$.subscribe(response => {
  let blobObj = response.body; // this should be your blob object (body of response)
  let headers = response.Headers //This is a disctionary/HashMap were you'll find the content-desposition header

//.....

})  

关于angular - 在 Angular 中下载具有原样文件名的 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54626162/

相关文章:

angular - 不能使用 Observable 作为 MatTable 的 DataSource,显示为空

javascript - 如何基于索引访问 Angular 4 中数组数组中的元素?

javascript - 使用 @ViewChild 按类名选择元素?

angular - 在 Firestore 中使用 Angular 删除集合中的文档

javascript - 更改管道中对象的属性(rxjs)

typescript - 使用 Create React App 和 TypeScript 进行 Jest 测试时的 isolatedModules 错误?

javascript - 在 Angular 的 ngOnChanges 中调用本地声明的函数

Angular 2 模板 - 方法的安全导航运算符

angular - 变量 'a' 隐式具有 'any[]' 类型

javascript - 已弃用的 Webpack 的 i18n 插件和加载器的替代品