兼容到ie10的js文件导出、下载到本地

话不多说,上代码:

try {
                let reader = new FileReader();
                let blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' });
                reader.readAsArrayBuffer(blob);
                reader.onload = function() {
                    let data = new Blob([this.result]);
                    // 判断是否为文件流数据
                    if (data.size === 0) this.$message({ message: '生成文件失败', type: 'error' });
                };
                let downloadElement = document.createElement('a');
                let href = window.URL.createObjectURL(blob); // 创建下载的链接
                let head = res.headers['content-disposition'];
                if (!head) {
                    this.$message({ message: '导出失败', type: 'error' });
                    return;
                }
                downloadElement.href = href;
                head = decodeURI(head.split(';')[1].split('=')[1]); // url转码中文
                downloadElement.download = head; // 下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); // 点击下载
                document.body.removeChild(downloadElement); // 下载完成移除元素
                window.URL.revokeObjectURL(href); // 释放掉blob对象
            } catch (e) {
                let head = res.headers['content-disposition'];
                head = decodeURI(head.split(';')[1].split('=')[1]); // url转码中文
                if ('msSaveOrOpenBlob' in navigator) {
                    window.navigator.msSaveOrOpenBlob(new Blob([res.data]), head);
                } else {
                    const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' }));
                    const link = document.createElement('a');

                    link.style.display = 'none';
                    link.href = url;
                    link.setAttribute('download', head);
                    document.body.appendChild(link);
                    link.click();
                }
            }

  

猜你喜欢

转载自www.cnblogs.com/webSong/p/10287007.html
今日推荐