搜索

首页  >  问答  >  正文

javascript - 如何在ie11里使用a连接创建动态下载文件流?

下面的函数,在其他浏览器里可以下载一个txt文件,但是在ie11里跳转到一个空白页面。文件被url编码后放在了地址栏。没有触发下载。请问怎么才能在ie11里也触发下载文件?

完整项目地址:https://github.com/wangduandu...

    this.downloadLog = function() {
        var file = "data:text/plain;charset=utf-8,";
        var logFile = self.getLog();
        var encoded = encodeURIComponent(logFile);
        file += encoded;
        var a = document.createElement('a');
        a.href = file;
        a.target   = '_blank';
        a.download = self.formatTimestamp()+ '-' + self.logFilename;
        document.body.appendChild(a);
        a.click();
        a.remove();
    };

phpcn_u1582phpcn_u15822794 天前589

全部回复(1)我来回复

  • PHPz

    PHPz2017-05-19 10:10:47

    查了资料,可以使用微软独家的msSaveBlob, 这个方法支持ie10及以上。

    var downloadFileName = self.formatTimestamp()+ '-' + self.logFilename;
    
            if(window.navigator.msSaveBlob){
                // for ie 10 and later
                try{
                    var blobObject = new Blob([self.output]); 
                    window.navigator.msSaveBlob(blobObject, downloadFileName); 
                }
                catch(e){
                    console.log(e);
                }
            }
            else{
                var file = "data:text/plain;charset=utf-8,";
                var logFile = self.output;
                var encoded = encodeURIComponent(logFile);
                file += encoded;
                var a = document.createElement('a');
                a.href = file;
                a.target   = '_blank';
                a.download = downloadFileName;
                document.body.appendChild(a);
                a.click();
                a.remove();
            }
    

    回复
    0
  • 取消回复