美文网首页
blob文件下载记录

blob文件下载记录

作者: 爱代码的派派星 | 来源:发表于2022-12-29 09:56 被阅读0次
    export function downloadBlob(
      data,
      name,
      type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ) {
      if (name) {
        if (name.lastIndexOf(".") < 0) {
          name += ".xlsx";
        }
      } else {
        name += ".xlsx";
      }
      let blob = new Blob([data], { type });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, name);
      } else {
        let objectUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.download = name;
        a.href = objectUrl;
        a.click();
        document.body.appendChild(a);
    
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);
        a.dispatchEvent(evt);
        document.body.removeChild(a);
      }
    }
    
    /**
     * 导出文件下载
     * @param  {[type]} res 后台返回response
     * @return {[type]}     [description]
     */
    export function exportDownload(that,res){
      if (res.data.type == 'application/json') {
          // 将blob文件流转换成json
          const reader = new FileReader();
          reader.readAsText(res.data);
          reader.onload = function (event) {
            const message = JSON.parse(event.target.result).message;
            that.$message.error(message);
          }
          return false;
        }
        const blob = new Blob([res.data]);
        let str = res.headers['content-disposition'];
        let filename = decodeURI(str.substr(str.indexOf('=') + 1));
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            //ie使用的下载方式
            window.navigator.msSaveOrOpenBlob(blob, filename);
         } else {
            let elink = document.createElement("a");
            // 设置下载文件名
            elink.download = filename;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:blob文件下载记录

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