【发布时间】:2018-06-22 20:22:35
【问题描述】:
我的网站有一些文档只有在登录后才能“下载”。所以当一个anchor元素被点击时,它需要附加authorization标题,然后API返回blob .为了添加授权标头,我使用了将anchor 元素上的href 替换为click 事件的解决方案。这是代码:
HTML
<a class="{{ anchorClasses }}" (click)="!downloadDocument(path)" href="">
<i *ngIf="iconClasses && iconClasses.length > 0" class="{{ iconClasses }}" aria-hidden="true"></i><span [innerHTML]="linkText"></span>
</a>
打字稿代码
downloadDocument(url: string) {
this.appDataService.spinnerService.show();
return this.anchorDocumentService.downloadDocument(url)
.subscribe((result: any) => {
this.downloadFileFromBlob(result, url);
return false;
}, (error: any) => {
console.error(error);
this.appDataService.spinnerService.hide();
this.appDataService.routeToErrorPage(error);
return false;
});
}
正如您将在订阅的函数成功回调中看到的那样,我立即调用“downloadFileFromBlob”函数,如下所示:
private downloadFileFromBlob(blob: any, url?: string) {
console.log('DownloadLinkComponent | downloadFileFromBlob...');
try {
const anchorDownloadUrl = window.URL.createObjectURL(blob);
const anchorDownload = document.createElement('a');
document.body.appendChild(anchorDownload);
anchorDownload.href = anchorDownloadUrl;
anchorDownload.setAttribute('style', 'display: none;');
anchorDownload.setAttribute('target', '_blank');
if (url && url.length > 0) {
anchorDownload.setAttribute('download', this.isDocumentService.getFilenameFromPath(url));
}
console.log('DownloadLinkComponent | downloadFileFromBlob | clicking the hidden download link...');
anchorDownload.click();
// anchorDownload.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
window.URL.revokeObjectURL(anchorDownloadUrl);
} catch (error) {
this.appDataService.routeToErrorPage(error);
} finally {
this.appDataService.spinnerService.hide();
}
}
所以,在chrome 中,这很好用。但是在 IE 中,它在这一行抛出了一个错误:
anchorDownload.click();
在 IE 中,显示的错误页面显示:
网页无法显示
Most likely cause: •Some content or files on this webpage require a program that you don't have installed.
这是我获得添加身份验证标头的代码的地方:How to set a header for a HTTP GET request, and trigger file download?
因此,在chrome 中,当该单击事件触发时,它会将 blob 下载到我的本地文件系统,并且该文件的 url 又名文件路径设置为 [隐藏] 的 href锚点点击事件。那么....为什么 IE 无法下载此文件?
【问题讨论】:
标签: javascript angular authorization angular5 anchor