zoukankan      html  css  js  c++  java
  • 兼容到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();
                    }
                }
    

      

  • 相关阅读:
    6月15日学习日志
    6月14日学习日志
    6月13日学习日志
    6月12日学习日志
    给建民哥的意见
    6月10日学习日志
    6月9日学习日志
    6月8日学习日志
    梦断代码读书笔记3
    第二次冲刺(六)
  • 原文地址:https://www.cnblogs.com/webSong/p/10287007.html
Copyright © 2011-2022 走看看