angular - 使用时文件下载损坏观察:角度服务中的响应
问题描述
当我在角度服务中使用观察:“响应”时。从标题中获取文件名并下载它。文件已损坏。
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',下载的文件是正确的。
解决方案
这很容易。您应该使用 success.body 而不是成功。
this.saveData(success.body, fileName);
因为当你使用observe:'response'时,接收到的数据类型发生了变化
推荐阅读
- visual-studio - 假的:使用 MSBuild 版本 16 (Visual Studio 2019)
- javascript - 查看一个数组有多少个值是相同的
- animation - SwiftUI - 使用 .easeInOut 为 ZStack 中的视图不透明度设置动画
- pandas - 通过 matplotlib 和 seaborn 将 pandas groupby 转换为图表
- url - werkzeug.routing.BuildError:无法为端点“结果”构建 url。您是否忘记指定值 ['search']?
- excel - 每隔 n 列使用 Target.Column
- php - Docker-compose 权限错误,chown 不起作用
- c - 为什么 FTDI 的这个 I2C 示例代码中有一个字地址?
- java - 如何通过 Telnet 发送字符串?
- python-3.x - numpy.matmul 给出的答案与@不同