angular - 在 Angular 6 中使用 HttpClient 下载文件
问题描述
当用户单击下载方法时,我必须在浏览器本身的 Angular 6 中使用 HttpClient 下载 csv 文件。
组件.service.ts
download():Observable<any[]>{
return this.http.get<any[]>(this.url+'/download/external');
}
组件.ts
onDownload(){
console.log("data is downloading");
this.service.download().subscribe(data=>{
let dataType = data;
let binaryData = [];
binaryData.push(data);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new
Blob(binaryData, {type:"application/ms-excel"}));
document.body.appendChild(downloadLink);
downloadLink.click();
})
}
作为回应,我收到此错误:
错误 HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: " http://localhost:8080/expocms/download/external ", ok: false, ...}
解决方案
你可以试试这样
onDownload(){
console.log("data is downloading");
this.service.download().subscribe(response=>{
const a = document.createElement('a');
document.body.appendChild(a);
const blob = new Blob([response], { type: 'octet/stream' });
// if octet/stream is not working then try this one application/ms-excel
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "filename.csv"; // you need to write the extension of file here
a.click();
window.URL.revokeObjectURL(url);
})
}
让我知道它是否有效
推荐阅读
- python - python if语句打印超过它应该
- php - 如何将 SQL 表数据存储到 PHP 2D 数组中?
- php - 如何在网站上显示 Instagram 照片
- php - 当没有其他输出发送到浏览器时,php 不会重定向到新页面
- java - 应该读取和存储捆绑包的 Android MVVM
- excel-formula - 如何计算给定最大值的excel中一组数字的平均值?
- javascript - Vue.js - 将一个输入字段与另一个交换,但保持相同的 v-model
- git - 我在一个目录中有一个当前的 PR。如何为该目录中的不同子目录创建单独的 PR?
- c# - 这个 Func 中的第一个箭头运算符是什么
意思是? - typescript - 如何在 Typescript 中声明多态数据接口?