axios请求设置responseType为‘blob‘或‘arraybuffer‘下载时,正确处理返回值

本文介绍如何在前端使用axios接收后台返回的图片数据,并将其转换为base64格式展示在img标签中,同时提供通过arraybuffer及blob格式处理图片流的方法。

问题:调用后台图片接口,后台返回二进制流图片数据格式。前端接收到流后处理数据显示在img标签。

解决:

1、设置axios接收参数格式为"arraybuffer":

responseType: 'arraybuffer'

2、转换为base64格式图片数据在img标签显示:

return 'data:image/png;base64,' + btoa(
    new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
  );

返回的string直接放在img标签src可直接显示

二、设置axios接收参数格式为"blob":

axios.post( ExportUrl, Params, {
    responseType: 'blob'
  })
  .then(function(response) {
    this.url = window.URL.createObjectURL(new Blob([response.data]));
    
  });

三、通过a标签下载文件

const url = '下载的url链接';
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.setAttribute('download', 'Excel名字.xlsx');
document.body.appendChild(link);
link.click();

responseType值的类型

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

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

①、请求设置为 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();
      }
    }

②、请求设置为 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
    }
你提到的这段代码: ```js const response = await axios.get(url, { params, responseType: 'arraybuffer', }); ``` 是用于确保 **axios 请求返回的是二进制文件流(如 Excel 文件)**,而不是字符串 JSON 格式。这是非常关键的一步,**否则前端无法正确解析并下载 Excel 文件。** --- ### ✅ 正确使用位置:封装在你的 `downloadFile` 函数中 你提到的 `downloadFile` 是你自己封装的 API 请求函数,应该在这个函数内部使用 `axios.get` 并设置 `responseType: 'arraybuffer'`。 --- ### ✅ 示例:如何封装 `downloadFile` ```js // @/api/comm.js 你的 api 文件中 import axios from 'axios'; export const downloadFile = async (url, params) => { const response = await axios.get(url, { params, responseType: 'arraybuffer', // 关键:确保返回的是二进制流 }); return response.data; // 返回原始二进制数据 }; ``` --- ### ✅ 确保你的 `onSelect` 方法中调用的是这个封装好的函数: ```js async onSelect(action) { this.$toast.loading({ message: '加载中...', forbidClick: true, }); let url = ''; let fileName = ''; if (action.text === '项目导出') { url = '/hdygwy/ygNoticePublish/notification/review/export'; fileName = '项目列表.xlsx'; } else if (action.text === '账号导出') { url = '/hdygwy/ygNoticePublish/notification/account/export'; fileName = '账号列表.xlsx'; } try { const response = await downloadFile(url, { noticeId: this.noticeId, orgCode: this.orgCode, userId: this.userId, }); const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); saveAs(blob, fileName); // 使用 file-saver this.$toast.success('导出成功'); } catch (error) { console.error('导出失败:', error); this.$toast.fail('导出失败,请检查网络重试'); } } ``` --- ### ✅ 为什么必须设置 `responseType: 'arraybuffer'`? | 浏览器/设备 | 默认 responseType | 是否支持 Excel 流 | 是否需要设置 `arraybuffer` | |------------|------------------|--------------------|-----------------------------| | PC 浏览器 | `json` | ✅ 有可能解析成功 | ❌ 有可以不设置 | | 移动端浏览器 | `json` | ❌ 极易解析失败 | ✅ 必须设置 | 如果不设置,移动端浏览器可能会将 Excel 二进制流当作 JSON 解析,导致解析失败,出现错误提示如: ``` 未能完成操作。(OfficeLmportErrorDomain错误912。)(null) ``` --- ### ✅ 总结:你应该在封装的 `downloadFile` 方法中设置 `responseType: 'arraybuffer'`,确保返回的是原始二进制数据,这样在 PC 和移动端都能正常下载 Excel 文件。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值