vue2简单的音频(mp3)+文本(.doc)导出

90 阅读1分钟

对于前端项目上,“导出文件”是一个很常见的业务,就对于像本人遇到的音频和文本的一键导出,因为比较特殊,我们这边的导出没有提供接口,所以就是自己在展示的页面上拿,所以对于dom结构的使用和理解得比较熟练。 直接上代码:
 download(url,name){
            var x = new XMLHttpRequest();
            x.open("GET", url, true);
            x.responseType = 'blob';
            x.onload=function(e) {
                            var url = window.URL.createObjectURL(x.response)
                            var a = document.createElement('a');
                            a.href = url
                            a.download = name;
                            a.click()
            }
            x.send();
        },
    async exportRecordList(id,selectItemId,retext1){
        this.text=retext1
        this.showExportPopup = false
        //获取页面上的dom节点
        let dom=document.getElementById('download_text')
        //按照导出的三种模式
        if(id==1){
        //创建一个a标签用于做真实的点击下载使用
         var textTag=document.createElement('a')
         //注意这里的写法,文本的导出需要这种特定写法
         textTag.href='data:text/plain;charset=utf-8,'+encodeURIComponent(dom.textContent)
         //这里是本人项目的导出文件名需要的格式需求
         textTag.download=this.recordType+"("+this.createTime+")"+".doc"
         this.download(this.audio,this.recordType+"("+this.createTime+")"+".mp3")
         textTag.click();
        }
        else if(id==2){
          this.download(this.audio,this.recordType+"("+this.createTime+")"+".mp3")
        }
        else if(id==3){
          var textTag=document.createElement('a')
          textTag.href='data:text/plain;charset=utf-8,'+encodeURIComponent(dom.textContent)
          textTag.download=this.recordType+"("+this.createTime+")"+".doc"
          textTag.click();
        }
    }
  },
};

这里为什么要这么写呢?是因为我们这里的导出分为三种

image.png 特别注意音频导出的文件名需要使用blob进行文件解析,才能给它赋名,直接this.download="哈哈哈哈.MP3"是不行的,所以通过这种方式进行赋名。 这里是DOM结构:

image.png