Angular 4 HttpModule如何从Get请求返回文件
我有一个RESTAPI,如果我直接在浏览器中查询,它将返回一个JSON或CSV文件供下载。我想对角度HttpModule做同样的事情 我的get请求很简单(它有一个查询字符串param来指示要返回的文件格式): 响应内容类型为Angular 4 HttpModule如何从Get请求返回文件,angular,Angular,我有一个RESTAPI,如果我直接在浏览器中查询,它将返回一个JSON或CSV文件供下载。我想对角度HttpModule做同样的事情 我的get请求很简单(它有一个查询字符串param来指示要返回的文件格式): 响应内容类型为application/octet-stream。我尝试将响应作为一个blob进行处理,但不起作用。如何将响应从服务器传递到浏览器,让它下载文件?此方法是响应按钮单击的组件调用的服务的一部分 onClick() { this._requestService.Subm
application/octet-stream
。我尝试将响应作为一个blob进行处理,但不起作用。如何将响应从服务器传递到浏览器,让它下载文件?此方法是响应按钮单击的组件调用的服务的一部分
onClick() {
this._requestService.Submit(request); //This gets the Subscription response from the service, but I want it to let the broswer download the file
}
您可以尝试以下方法:
this.http.get(url).subscribe(response => {
const blob = new Blob([response], { type: 'text/csv' });
const url= window.URL.createObjectURL(blob);
window.open(url);
});
我从和得到了大部分解决方案 对于非IE浏览器(“else”语句),我也能够成功地使用
let reader = new FileReader();
reader.onloadend = function () {
window.location.href = reader.result;
};
reader.readAsDataURL(blob);
对于第二种方法,blob类型必须是application/octet stream
,否则对于application/json
或text/csv
之类的内容,它将在新窗口/选项卡中打开文件。缺点是您无法提供文件名或扩展名,因此会得到一个名为“下载”的原始文件。您必须添加
{ responseType: ResponseContentType.Blob }
然后将响应映射到blob
return this.http.get(url, { responseType: ResponseContentType.Blob })
.map(r => r.blob())
.subscribe(response => {
});
接下来,您可以使用fileSaver.js下载此文件。尝试了此操作后,我得到一个错误:
资源“blob:6BB5A3D5-0D0D-4537-B4F3-888D7A70DE57”不允许加载。
{ responseType: ResponseContentType.Blob }
return this.http.get(url, { responseType: ResponseContentType.Blob })
.map(r => r.blob())
.subscribe(response => {
});