Angular2+ 使用 Post 请求下载文件

一般遇到下载文件的需求,我们使用 window.open(url) 方法传入后台对应接口地址即可打开新窗口触发下载。

但是常常有参数过大等情况我们不得不使用 Ajax 来解决问题,可是 Ajax 并不会触发浏览器的下载,就需要我们曲线救国了。

动态生成一个带下载地址的标签元素 <a>,被动触发点击事件,进而触发浏览器下载行为。

// post请求
getFileDownload(){
    return this.http.post(url, [params], { responseType: 3 })
        .map(res => res.json())
        .catch(this.conf.handleError)
}
// ts中调用
downloadFile(){
    this.download.getFileDownload()
        .subscribe(res => {
            let blob = new Blob([res])
            let objectUrl = URL.createObjectURL(blob);  
            let a = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display:none');
            a.setAttribute('href', objectUrl);
            a.setAttribute('download', [fileName]);
            a.click();
            URL.revokeObjectURL(objectUrl); 
        })
}

参考:https://www.cnblogs.com/liugang-vip/p/7016733.html