download() { const token = localStorage.getItem('token'); let headers: HttpHeaders = new HttpHeaders(); headers = headers .set('Authorization', 'Bearer ' + token); const url = 'http://localhost:8764/api/v1/user/downLoadZipFile'; this.http.get(url, {headers: headers, observe: 'response', responseType: 'blob'}).subscribe(response => { console.log(response); console.log(response.headers.keys()); this.downloadFile(response); }, (error: HttpErrorResponse) => { console.log(error.error); }); } downloadFile(data: HttpResponse<Blob>) { const file = new Blob([data.body], {type: 'application/zip'}); const a = document.createElement('a'); a.id = 'tempId'; document.body.appendChild(a); a.download = 'haha.zip'; a.href = URL.createObjectURL(file); a.click(); const tempA = document.getElementById('tempId'); if (tempA) { tempA.parentNode.removeChild(tempA); } } }
var blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); var objectUrl = URL.createObjectURL(blob); var 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);
通用下载代码JS:
downloadFile(filePath: any) { this.meetingService.downloadFile(filePath, rtv => { if (rtv) { let _blob = new Blob([rtv]); let _filename = filePath.substring(filePath.lastIndexOf('_') + 1); if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(_blob, _filename); } else { let _link = document.createElement('a'); let _url = window.URL.createObjectURL(_blob); document.body.appendChild(_link); _link.setAttribute('style', 'display:none'); _link.href = _url; _link.download = _filename; _link.click(); window.URL.revokeObjectURL(_url); _link.remove(); } } else { alert('下载失败,请稍后重试!'); } }); }
参考文章:
https://www.cnblogs.com/liugang-vip/p/7016733.html