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
    }
### 使用 AxiosInstance 设置 responseType 为 `blob` 类型的方法 为了实现通过 AxiosInstance 下载二进制数据(如文件),需要显式地将 `responseType` 设置为 `'blob'`。这可以通过在创建 Axios 实例者发起具体请求指定该参数来完成。 #### 1. **创建带有预设 `responseType` 的 AxiosInstance** 如果大多数请求都需要以 `blob` 形式接收响应,可以在初始化 AxiosInstance 全局设置 `responseType` 参数: ```javascript import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://example.com/api', // 替换为实际的基础 URL timeout: 10000, headers: { 'Content-Type': 'application/json' }, responseType: 'blob' // 全局设置 responseTypeblob }); ``` 这样,在使用此实例发送任何请求,默认都会尝试解析成 `Blob` 对象[^1]。 #### 2. **单独请求中动态设置 `responseType`** 对于某些特殊情况下只需要某次请求返回 `Blob` 数据的情况,则无需修改整个实例配置,只需在单个请求的选项对象中覆盖 `responseType` 即可: ```javascript axiosInstance.post('/download-file', requestData, { responseType: 'blob' }).then(response => { const fileUrl = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = fileUrl; link.setAttribute('download', 'filename.ext'); // 自定义下载后的文件名 document.body.appendChild(link); link.click(); }).catch(error => { console.error("Error downloading the file:", error.response ? error.response.data : error.message); }); ``` 这里展示了如何手动触发浏览器保存由服务器传回的数据流作为本地文件的操作过程[^3]。 #### 3. **解决可能遇到的问题 - 动态调整 `responseType`** 当面对既需支持正常 JSON 格式的错误反馈又希望获取成功状态下的二进制资源这种需求,可通过条件判断逻辑先试探性读取结果再决定下一步动作: ```javascript function fetchResource(url, options={}) { return axiosInstance.get(url, {...options}) .catch((error) => { if (!error || !error.response){ throw new Error(`Network issue occurred while fetching resource at ${url}`); } try{ const parsedJson = JSON.parse(error.response.data); // 如果能被解析成JSON就认为这是预期内的错误消息 throw new CustomApiError(parsedJson.code,parsedJson.msg||parsedJson.message); } catch(e){ // 否则重新抛出原始异常让调用方自行处理未知情况 throw e ; } }); } fetchResource("/path/to/resource",{responseType:"arraybuffer"}) .then(blobData=>{/*...*/}) .catch(customErr=>{ alert(`${customErr.getCode()} - ${customErr.getMessage()}`) }); ``` 上述例子演示了一个较为复杂的场景:首先尝试加载目标地址的内容;一旦发生异常便检查是否有可用的结构化错误提示可供展示给最终用户[^2]。 --- ### 注意事项 - 确保后端正确设置了 MIME 类型和 Content-Disposition 头部字段以便前端能够识别所传递过来的确切文档类别及其推荐存储名称。 - 浏览器兼容性方面需要注意较老版本可能存在不同程度的支持缺失现象,请提前测试验证目标环境是否满足最低要求。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值