axios 导出excel---提示文件损坏解决方案

本文档介绍了在不使用Mock时如何处理axios请求以下载文件,特别是将responseType设置为'blob'或'arraybuffer'。同时,当使用Mock模块导致responseType设置无效时,提供了修改Mock源码的解决方案,即在指定行数添加代码来保持responseType设置。
摘要由CSDN通过智能技术生成

没有使用Mock时解决办法

axios请求部分

将 responseType 设置为 ‘blob’或’arraybuffer’

responseType类型
详细讲解
在这里插入图片描述

export function DowExcle(data) {
  return requestServer({
    headers: {
      'Content-Type': 'application/json; application/octet-stream'
    },
    url: '/excel/export/',
    method: 'get',
    responseType: 'blob'
  })
}
下载文件部分
deviceDowExcle().then((res) => {

  console.log(res);
  
  const fileName = res.headers['content-disposition'].split("'")[2];
  
  const _res = res.data;
  
  const blob = new Blob([_res]);
  
  const downloadElement = document.createElement('a');
  
  const url = window.URL || window.webkitURL || window.moxURL
  
  const href = url.createObjectURL(blob); // 创建下载的链接
  
  downloadElement.href = href;
  
  downloadElement.download = decodeURI(fileName); // 下载后文件名

  document.body.appendChild(downloadElement);

  downloadElement.click(); // 点击下载

  document.body.removeChild(downloadElement); // 下载完成移除元素

  url.revokeObjectURL(href); // 释放掉blob对象
});

使用了Mock模块时解决办法

原因

使用了Mockjs后会对responseType 进行初始化,所以一直设置不上responseType

解决方案

  1. 停止使用Mock数据,删除对Mock的引用

  2. 改下源码 mockjs - dist - mock.js 8362行下面加一行代码

     this.custom.xhr.responseType = this.responseType
    

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值