[英]Download excel file in angular 7 using a blob url
我正在嘗試使用 mime 類型“ data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ”在我的 angular 7 應用程序中下載 excel 文件,但是當我嘗試打開下載的文件時,它拋出了一些錯誤說 - http://prntscr.com/ur1nc4 。
這是我為了下載文件所做的工作
const filePath = "https://bviewstorage.blob.core.windows.net/9be306d9-acb1-4f25-a54f-5126e021ec6d/hrm/aabe5bd4-940a-4246-979c-581fdaa45808/Client_export_1592830934796-94f5d780-4007-4ae6-b802-53f4fe5509f2.xlsx"
const linkSource = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet," + filePath;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = "ExcelTemplate" + this.datePipe.transform(new Date(), "yyyy-MM-dd") + ".xlsx";
downloadLink.click();
我什至嘗試下載文件路徑“xls”MIME 類型,但仍會引發相同的錯誤。
請告訴我下載excel文件的方法。
添加appenchild
,它應該可以工作。
document.body.appendChild(downloadLink);
downloadLink.click();
對於 IE,請這樣做:
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(url, filename);
}
const filePath = "https://bviewstorage.blob.core.windows.net/9be306d9-acb1-4f25-a54f-5126e021ec6d/hrm/aabe5bd4-940a-4246-979c-581fdaa45808/Client_export_1592830934796-94f5d780-4007-4ae6-b802-53f4fe5509f2.xlsx"
if(window) {
window.open(filePath);
}
由於您的文件不安全,可以使用上述代碼下載。 window.open 打開一個新的瀏覽器窗口,它將直接從 blob 下載文件。
對上述解決方案的評論的擴展
submitForm(): void { this.myFormPost.nativeElement.submit(); }
<form ngNoForm #myFormPost name="myFormPost" action="{{ backend API Here }}" method="POST" target="_blank" > <input type="hidden" [name]="'token'" [value]="use this to pass token" /> </form> <a href="javascript:void(0);" (click)="submitForm()" ><i class="fas fa-download" *ngIf="isDownload"></i>Download File</a >
用於處理 blob 數據下載的 Angular 代碼。
function downloadFile(filePath) {
var link = document.createElement('a');
link.href = filePath;
link.onclick = function() {
document.body.innerText = "Downloading";
setTimeout(function() {
document.body.innerText = "";
}, 2000);
}
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
downloadFile("https://bviewstorage.blob.core.windows.net/9be306d9-acb1-4f25-a54f-5126e021ec6d/hrm/aabe5bd4-940a-4246-979c-581fdaa45808/Client_export_1592830934796-94f5d780-4007-4ae6-b802-53f4fe5509f2.xlsx");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.