axios下载文件流处理返回值

本文详细介绍了如何使用Axios在不同的responseType设置下(arraybuffer与blob)处理文件下载,包括当后端错误返回json而非文件流时的解决策略。通过示例代码展示了如何判断并处理这两种情况,确保正确下载文件或展示错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 axios 请求 api 下载导出一个文件时,接口返回值可能会出现两种情况:
1、文件流
2、json 对象

responseType 值的类型

数据类型
''DOMString(默认类型)
arraybufferArrayBuffer 对象
blobBlob 对象
documentDocumnet 对象
jsonJavaScript object, parsed from a JSON string returned by the server
textDOMString

实例

返回值不同情况的处理方式,举例如下:

1.请求设置为 responseType: ‘arraybuffer’

请求成功时,后端返回文件流,正常导出文件;
请求失败时,后端返回 json 对象,如:{“Status”:“false”,“StatusCode”:“500”,“Result”:“操作失败”},也被转成了 arraybuffer

此时请求成功和失败返回的 http 状态码都是 200

解决方案: 将已转为 arraybuffer 类型的数据转回 Json 对象,然后进行判断

代码如下

async downloadFile (file) {
      let res = await this.$axios.post(this.API.order.tradeImpExcle, { responseType: "arraybuffer" });
      if (!res) return;
      try {
        //如果JSON.parse(enc.decode(new Uint8Array(res.data)))不报错,说明后台返回的是json对象,则弹框提示
        //如果JSON.parse(enc.decode(new Uint8Array(res.data)))报错,说明返回的是文件流,进入catch,下载文件
        let enc = new TextDecoder('utf-8')
        res = JSON.parse(enc.decode(new Uint8Array(res.data))) //转化成json对象
        if (res.Status == "true") {
          this.refresh()
          this.$message.success(res.Msg)
        } else {
          this.$message.error(res.Result)
        }
      } catch (err) {
        const content = res.data;
        const blob = new Blob([content]);
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute(
          "download",
          res.headers["content-disposition"].split("=")[1]
        );
        document.body.appendChild(link);
        link.click();
      }
    }
2.请求设置为 responseType: ‘blob’

解决方案: 将已转为 blob 类型的数据转回 Json 对象,然后进行判断

代码如下

    async downloadFile (file) {
      let formData = new FormData();
      formData.append("allTradesExcelFile", file);
      let res = await this.$axios.post(this.API.order.tradeImpExcle, formData, { responseType: "blob" });
      if (!res) return;
      let r = new FileReader()
      let _this = this
      r.onload = function () {
        try {
          // 如果JSON.parse(this.result)不报错,说明this.result是json对象,则弹框提示
          // 如果JSON.parse(this.result)报错,说明返回的是文件流,进入catch,下载文件
          res = JSON.parse(this.result)
          if (res.Status == "true") {
            _this.refresh()
            _this.$message.success(res.Msg)
          } else {
            _this.$message.error(res.Result)
          }
        } catch (err) {
          const content = res.data;
          const blob = new Blob([content]);
          let url = window.URL.createObjectURL(blob);
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute(
            "download",
            res.headers["content-disposition"].split("=")[1]
          );
          document.body.appendChild(link);
          link.click();
        }
      }
      r.readAsText(res.data) // FileReader的API
    }

转自:https://blog.youkuaiyun.com/lhz_333/article/details/102495755

使用download.js下载
import axios from 'axios';
import download from 'downloadjs';
import { format } from 'date-fns'; //格式化时间模块

axios.post('http://www.lihefei.com', {
    name: 'lihefei'
}, {
    responseType: 'blob' //设置接口响应返回的数据流类型
}).then(response => {

    let blob = resolve.data; //文件数据流
    
    let timestamp = format(new Date(), 'yyyyMMddHHmmss') + new Date().getMilliseconds(); //当前年月日时分秒毫秒时间戳,例:2020070818090274
    
    let fileName = timestamp + '.xls'; //文件名,例:2020070818090274.xls
    
    let mimeType = 'application/vnd.ms-excel'; //xls格式文件对应的类型为:application/vnd.ms-excel

    download(blob, fileName, mimeType); //下载文件

}).catch(function (err) {
    console.log(err);
});

文件格式与类型对照表:https://lihefei.blog.youkuaiyun.com/article/details/101445668

其他方式
axios.post('http://www.lihefei.com', {
    name: 'lihefei'
}).then(response => {
    const blob = response;
    const reader = new FileReader();
    reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
    reader.onload = function (e) {
        // 转换完成,创建一个a标签用于下载
        const a = document.createElement("a");
        a.download = "test.xls";
        a.href = e.target.result;

        const body = document.querySelector('body');
        body.append(a); // 修复firefox中无法触发click
        a.click(); //触发点击下载
        
        body.removeChild(a); 
        
    };
}).catch(function (err) {
    console.log(err);
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值