美文网首页
IE11浏览器下载文件报错拒绝访问,兼容性处理

IE11浏览器下载文件报错拒绝访问,兼容性处理

作者: IsYang | 来源:发表于2020-04-20 14:19 被阅读0次

原始代码,是先创建一个a标签,然后在生成一个url地址,在设置下载属性,添加到DOM节点中,操作点击事件,完了之后在移除a标签节点。

核心代码如下:

   const blob = new Blob([res.data]);
   const a = document.createElement('a');
   a.href = window.URL.createObjectURL(blob);
   a.download = fileName;
   document.body.appendChild(a);
   a.click();
   document.body.removeChild(a);

使用IE11浏览器导出报错拒绝访问如下


image.png

在控制台看了一下生成的节点,发现a标签已经生成了,却发现a标签的下载属性未添加, 未实现点击这一动作。

<a href="blob:5567C153-E677-4F45-9DB8-18C407E00880"></a>

使用 window.navigator.msSaveBlob(blob, defaultName) 代码,去保存下载文件。

解决兼容性处理代码如下

        exportTable () {
            this.loading = true;
            let qusMethod = this.method == 'get' ? 'getDownAjax' : 'postAjax';  // 请求方式判断(只考虑get和post两种方式)
            http[qusMethod](
                this.url,
                this.params,
                { responseType: 'blob'}
            ).then(res => {
                if(res.status === 200) {
                    this.loading = false;
                    const blob = new Blob([res.data]);
                    let ext = this.ext  || 'xlsx';
                    let fileName = `${this.filename}-${moment().format('YYYYMMDDHHmmss')}.${ext}`;
                    // ie兼容处理
                    if (window.navigator.msSaveBlob) {
                        window.navigator.msSaveBlob(blob, fileName);
                    } else {
                        const a = document.createElement('a');
                        a.href = window.URL.createObjectURL(blob);
                        a.download = fileName;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    }
                } else {
                    this.$message.error("请刷新页面重试!");
                }

            }).catch(error => {
                console.log(error);
            })
        }

相关文章

网友评论

      本文标题:IE11浏览器下载文件报错拒绝访问,兼容性处理

      本文链接:https://www.haomeiwen.com/subject/ozarihtx.html