angular 使用blob二進制流的方式下載后台文件


轉自https://blog.csdn.net/shengandshu/article/details/81127279

 

先說兩個比較古老的js下載方式,

1. window.open(src)和window.location = src

2. form表單提交

這兩個方式都有局限性,對於需要傳遞大量參數的下載請求,可以這樣寫:

this.http.post(`${this.uri}/exportdata.file`, params, {responseType: 'blob'}).subscribe(data => {
const link = document.createElement('a');
const blob = new Blob([data], {type: 'application/zip'});
link.setAttribute('href', window.URL.createObjectURL(blob));
link.setAttribute('download', new Date().getTime() + '.zip');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
這里通過設置 responseType: 'blob' 獲取了文件的二進制流,再通過a標簽的方式模擬點擊下載。

這種下載方式有兩點需要注意:

1. 下載的文件格式需要確定

上面的例子下載的是zip格式,如果是其他格式,需要改變Content-Type(代碼第三行) 以及 文件名后綴(第五行)。比如:

 'doc'        => 'application/msword',

 'xls'        => 'application/vnd.ms-excel',

2. 文件名是前端命名還是后端命名

前端命名的話上面的代碼就可以了,如果需要后端命名,首先需要后端在響應頭中帶上文件名,比如:

Content-disposition: attachment; filename=file_201807201030327711.zip
再對上面的post請求做一下修改:

this.http.post(`${this.uri}/exportdata.file`, params, {responseType: 'blob', observe: 'response'}).subscribe(data => {
const link = document.createElement('a');
const blob = new Blob([data.body], {type: 'application/zip'});
link.setAttribute('href', window.URL.createObjectURL(blob));
link.setAttribute('download', data.headers.get('Content-disposition').split('filename=')[1]);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
通過設置 observe: 'response' 獲取到返回的響應頭,再獲取其中的文件名。
————————————————
版權聲明:本文為CSDN博主「shengandshu」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/shengandshu/article/details/81127279


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM