在angular 6中使用HttpClient下载文件

时间:2019-03-29 09:20:07

标签: angular

当用户单击下载方法时,我必须在浏览器自身内部的angular 6中使用HttpClient下载CSV文件。

component.service.ts

download():Observable<any[]>{
  return this.http.get<any[]>(this.url+'/download/external');
}

compononent.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();
     })

   }

作为回应,我收到此错误:

ERROR HttpErrorResponse {header:HttpHeaders,status:200,statusText:“ OK”,url:“ http://localhost:8080/expocms/download/external”,ok:false,...}

1 个答案:

答案 0 :(得分:0)

您可以尝试

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

让我知道它是否正常运行