首页 > 解决方案 > 在 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, ...}

标签: angular

解决方案


你可以试试这样

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);
 })
}

让我知道它是否有效


推荐阅读