如何把后端返还的blob格式的文件进行本地下载?

代码的请求思路:请求后端接口,返还blob文件。
qs.stringify 是把一个参数对象格式化为一个字符串。

 axios({
	 method: "get",
	   url: `/api/list/download?${qs.stringify(params)}`,
	   headers: {
	     Authorization: "Bearer " + accessToken,
	   },
	   responseType: "blob",
 }).then(()=>{

 })

返还文件下载思路:
判断文件返还的格式类型,使用前端a链接的方式进行前端单个文件下载功能的实现。

import { ElMessage  } from "element-plus";
export function readFileDownload(data, msg) {
  var res = data;
  if (
    res.type === "application/json" ||
    res.type === "application/json;charset=UTF-8"
  ) {
    // 失败的时候,注意ie兼容问题
    let fileReader = new FileReader();
    fileReader.onload = function () {
      let jsonData = JSON.parse(this.result); // this.result是根据event,读取文件后打印的     event.target.reslut
      if (jsonData.data === null && jsonData.status === 400) {
        ElMessage({
          message : jsonData.message || "Error",
          type: "error",
          duration: 5 * 1000,
        });
      }
    };
    fileReader.readAsText(res);
  }
  if (
    res.type === "application/octet-stream" ||
    res.type === "application/vnd.ms-excel" ||
    res.type === "application/vnd.ms-exce" ||
    res.type === "application/vnd.ms-excel;charset=UTF-8" ||
    res.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ) {
    console.log("success..."); // 成功,注意ie兼容问题

    const blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8",
    });

    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, msg);
    } else {
      console.log(blob);
      const url = window.URL.createObjectURL(blob);
      console.log(url);
      const aLink = document.createElement("a");
      aLink.style.display = "none";
      aLink.href = url;
      aLink.setAttribute("download", msg);
      document.body.appendChild(aLink);
      aLink.click();
      document.body.removeChild(aLink);
      window.URL.revokeObjectURL(url);
    }
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值