Vue--导出文件流遇到的问题

文件导出失败

解决方案:
1.设置头部
2.接受blob流

 headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8"
    headers["responseType"] = "blob"

在这里插入图片描述

导出文件流+文件名乱码

文件名可以自己起或者后端传过来的转一下

   //导出
        if (response.config && response.config.responseType == "blob") {
          //   const excelUrl = window.URL.createObjectURL(new Blob([response.data]));
          //   const link = window.document.createElement('a');
          let fileName = (response.headers['content-disposition'].split('filename="')[1]).split('"')[0]; // 文件名
          //对文件名乱码转义--【Node.js】使用iconv-lite解决中文乱码
          let iconv = require('iconv-lite');
          iconv.skipDecodeWarning = true; //忽略警告
          fileName = iconv.decode(fileName, 'UTF-8');
          //   link.href = response.data;
          //   link.download = fileName;
          //   document.body.appendChild(link); // 兼容FireFox
          //   link.click();
          //   window.URL.revokeObjectURL(excelUrl);
          //   link.remove(); // 兼容FireFox

          let blob = new Blob([response.data], {
            type: "application/vnd.ms-excel"
          });
          let elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.target = "_blank";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL对象
          document.body.removeChild(elink);
        }

在这里插入图片描述

导出失败的时候 blob流 转 json

 if (error.response.config && error.response.config.responseType == "blob") {
          //导出失败
          let reader = new FileReader();
          reader.readAsText(error.response.data, 'utf-8');
          reader.onload = (e) => {
            console.log("----", JSON.parse(reader.result));
            console.log("----", JSON.parse(e.target.result));
            Message({
              message: JSON.parse(reader.result).msg || JSON.parse(e.target.result).msg,
              type: 'error',
              offset: 30,
              duration: 5 * 1000,
            })
          }
          return

        }

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值