Vue2 导出Excel + 解决乱码问题 —— axios (下载后台传过来的流文件(excel)后乱码问题)

接口要求: post方法、入参为json格式、出参文件流

这个是个反例:axios.post(url, params).then这个是下载之后乱码 不知为啥

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

下面这样的方式可以实现不乱了 axios API 可以通过向 axios 传递相关配置来创建请求
axios:设置返回数据格式为 blob 或者 arraybuffer ( 注意 )

axios({ // 用axios发送post请求
     method: 'post',
      url: ' /serviceTime/exportData', // 请求地址
      data: form, // 参数
      responseType: 'blob', // 表明返回服务器返回的数据类型
      headers: {
     'Content-Type': 'application/json'
     }
   }).then(res => { // 处理返回的文件流
     const blob = new Blob([res.data]);//new Blob([res])中不加data就会返回下图中[objece objece]内容(少取一层)
     const fileName = '统计.xlsx';//下载文件名称
     const elink = document.createElement('a');
     elink.download = fileName;
     elink.style.display = 'none';
     elink.href = URL.createObjectURL(blob);
     document.body.appendChild(elink);
     elink.click();
     URL.revokeObjectURL(elink.href); // 释放URL 对象
     document.body.removeChild(elink);
 })

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值