首页 > 解决方案 > 使用时文件下载损坏观察:角度服务中的响应

问题描述

当我在角度服务中使用观察:“响应”时。从标题中获取文件名并下载它。文件已损坏。

 return this.http.get(url, {observe: 'response', responseType: 'blob'});

    downloadLicenseFile() {
        let fileName;
        this.loading = true;
        this.licenseService.downLoadFile().subscribe(
            (success) => {
                fileName = success.headers.get('content-disposition').split('filename=')[1].replace(/['"]+/g, '');
                this.loading = false;
                this.validateNext = false;
                this.saveData(success, fileName);
            }, () => {
                this.validateNext = true;
                this.loading = false;
            });
    }


    saveData(data, fileName) {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style.display = 'none';
        const blob = new Blob([data], { type: 'application/gzip' });
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    }

如果我删除observe: 'response',下载的文件是正确的。

标签: angularservice

解决方案


这很容易。您应该使用 success.body 而不是成功。

this.saveData(success.body, fileName);

因为当你使用observe:'response'时,接收到的数据类型发生了变化


推荐阅读