一般遇到下載文件的需求,我們使用 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);
})
}