通过锚Angular 5下载文档在IE中不起作用

时间:2018-06-22 20:22:35

标签: javascript angular authorization angular5 anchor

我的网站上有些文件只有登录后才能“下载”。因此,当单击anchor元素时,它需要附加authorization标头,然后API返回blob。为了添加授权标头,我使用了将href元素上的anchor替换为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(也称为文件路径)被设置为{{1} }用于[隐藏]锚点事件。所以...为什么IE无法下载此文件?

1 个答案:

答案 0 :(得分:0)

我不确定是否应该将其关闭,还是不确定答案的链接...所以这是我找到的答案的链接:

blob download not working in IE

此修补程序仅需两行代码:

if (navigator.appVersion.toString().indexOf('.NET') > 0)
        window.navigator.msSaveBlob(blob, filename);
else
        const anchorDownloadUrl = window.URL.createObjectURL(blob);
        const anchorDownload = document.createElement('a');
        // ... the rest of the code in the 'downloadFileFromBlog' function

因此,只需快速检查一下我们是否在IE中运行,如果是的话,只需调用保存功能即可。