本文介绍了Angular:如何从 HttpClient 下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从我的后端下载一个 excel,它返回了一个文件.
I need download an excel from my backend, its returned a file.
当我执行请求时出现错误:
When I do the request I get the error:
TypeError:您在需要流的地方提供了未定义".你可以提供 Observable、Promise、Array 或 Iterable.
我的代码是:
this.http.get(`${environment.apiUrl}/...`)
.subscribe(response => this.downloadFile(response, "application/ms-excel"));
我尝试过 get 和 map(...) 但没有奏效.
I tried get and map(...) but didn't work.
详细信息:angular 5.2
参考:
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';
响应的内容类型:
Content-Type: application/ms-excel
怎么了?
推荐答案
试试这个:
类型:应用程序/ms-excel
/**
* used to get file from server
*/
this.http.get(`${environment.apiUrl}`,{
responseType: 'arraybuffer',headers:headers}
).subscribe(response => this.downLoadFile(response, "application/ms-excel"));
/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
let blob = new Blob([data], { type: type});
let url = window.URL.createObjectURL(blob);
let pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert( 'Please disable your Pop-up blocker and try again.');
}
}
这篇关于Angular:如何从 HttpClient 下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!