【问题标题】:download file using HttpClient in angular 6在 Angular 6 中使用 HttpClient 下载文件
【发布时间】:2019-08-20 04:45:38
【问题描述】:

当用户点击下载方法时,我必须在浏览器本身的 Angular 6 中使用 HttpClient 下载 csv 文件。

component.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


    【解决方案1】:

    你可以这样试试

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

    让我知道它是否有效

    【讨论】:

    • 嗨 Yash,很抱歉给您带来不便,但此代码在这两种解决方案中都不起作用。您能否为此提供一些替代方案。
    • 我遇到了同样的错误。错误 HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "localhost:8080/expocms/download/external", ok: false, ...}
    • 你能给我你的响应吗 api this.service.download().subscribe(res { console.log(res); }) 这样我就可以确定出了什么问题
    • 您能否举个例子,或者您可以在此处添加答案,以便其他开发人员可以从您的答案中获得帮助。如果我的回答对你有帮助,请接受我的回答
    猜你喜欢
    • 1970-01-01
    • 2019-05-12
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多