[英]Angular 9 - how to download and open an Excel file?
我有一個下載 Excel 文件的應用程序。 客戶端已請求下載后自動打開文件。 我希望有人能告訴我我做錯了什么。
URL.createObjectURL function 在下載文件夾中創建一個沒有擴展名的文件。 如果我添加 .xlsx 擴展名,我發現它是正確的 Excel 文件。 但是,如果我嘗試打開生成的 URL,則會出現路由錯誤:
ERROR 錯誤:未捕獲(在承諾中):錯誤:無法匹配任何路由。 URL 段:'ac88e37b-88a0-4a77-ac76-ecaddca74e39
下面的代碼片段顯示了現有的代碼——它確實有效——在下面我嘗試自動打開文檔的嘗試失敗了。
非常感謝任何幫助-謝謝-喬恩。
downloadExcel() {
this.dataRepositoryService.downloadExcel()
.then( (response) => {
// This is the existing code,
// which works and downloads the file to the downloads folder
let documentName:string = 'download-test.xlsx';
saveAs(response, documentName);
// I wish to replace the above
// with code that will automatically open the downloaded file
var url = URL.createObjectURL(response);
console.log("url: ", url);
window.open(url);
} )
.catch( (error:any) => console.error(error) );
}
試試下面的代碼。
downloadFile(data: Response) { const blob = new Blob([data], { type: 'application/octet-stream' }); const url= window.URL.createObjectURL(blob); window.open(url); }
這不是我想要的,但這很有效,客戶對解決方案很滿意。 我沒有嘗試使用代碼打開文件,而是下載它並告訴 chrome 自動打開該類型的文件:
保存下載:
downloadExcel() {
this.dataRepositoryService.downloadExcel()
.then( (response) => {
let documentName:string = 'download-test.xlsx';
saveAs(response, documentName);
} )
.catch( (error:any) => console.error(error) );
}
然后按照這篇文章中的描述讓 chrome 自動打開它:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.