【问题标题】:How to download xls or xlsx file in angular6 (Blob API response)如何在 angular6 中下载 xls 或 xlsx 文件(Blob API 响应)
【发布时间】:2019-12-29 17:48:09
【问题描述】:

我试图下载在 API 响应中作为 blob 接收的 XLSX 文件,但它被接收为HttpErrorResponse

这是由于angular5的请求结构发生了变化。

我已经尝试过使用 HttpErrorReponse 对象响应的请求,如下所示:

myBlobRequest():Observable<any>{
return this.http.get(url, { responseType: 'blob'})
            .map((response: Response) => {
                return response;
            })
            .catch((res: Response) => {
                // handleError(response)
            });
}

【问题讨论】:

    标签: angular6 blob xlsx


    【解决方案1】:

    以下解决方案对我有用。因为它在 HttpErrorResponse

    中给出了 json 解析错误

    解决方案

    { responseType: 'blob'} should be replaced with { responseType: 'blob' as 'json'}

    请求:

    GET方法:

    myBlobRequest():Observable<any>{
    return this.http.get(url, { responseType: 'blob' as 'json' })
                .map((response: Response) => {
                    return response;
                })
                .catch((res: Response) => {
                    // handleError(response)
                });
    }
    

    回应:

    在订阅者函数中处理:

    • 带有文件保护程序库:
    this.serviceObj.myBlobRequest.subscribe((blobResponse)=>{
                var blob = new Blob([resp], { type: 'application/vnd.openxmlformats- 
                           officedocument.spreadsheetml.sheet;' });
                FileSaver.saveAs(blob, "test.xlsx");
    });
    
    • 没有文件保护程序库:
    this.serviceObj.myBlobRequest.subscribe((blobResponse)=>{
                var blob = new Blob([resp], { type: 'application/vnd.openxmlformats- 
                           officedocument.spreadsheetml.sheet;' });
                // Download File without FileSaver
                const downloadUrl = window.URL.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = downloadUrl;
                link.download = "test.xlsx";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
    
    });
    

    【讨论】:

    • 这毫无意义。添加as 'json' 只是在向编译器撒谎,告诉编译器会调用哪个重载,而且您的地图回调完全没有意义。如果想在 HttpClient 中获取响应对象,见angular.io/guide/http#reading-the-full-response
    • @jonrsharpe,谢谢你的建议。这个解决方案对我有用,因为在我的情况下,收到了 HttpErrorResponse 对象并在 error.error >> json parse error 中显示。
    猜你喜欢
    • 2021-09-22
    • 2019-09-15
    • 2014-11-15
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多