vue中转换base64文件数据后通过blob下载

可以看到这里我要转换的数据是content字段,即将base64文件数据转换后下载下来:

downloadAttachment({ attachmentId: id })
    .then(({ data }) => {
      proxy.$modal.closeLoading();
      // atob先解码base64数据
      const raw = window.atob(data.content);
      // 获取解码后的字符串长度
      const rawLength = raw.length;
      // 初始化一个 8 位无符号整型数组
      const uInt8Array = new Uint8Array(rawLength);
      // 将每个解码字符转换为unicode编码再存入数组中
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      // 通过blob格式将数组转换成你想要的类型文件,第二个是类型
      const blob = new Blob([uInt8Array], { type: data.contentType });
      // 创建一个a标签在页面中实现下载
      const elink = document.createElement("a");
      elink.download = data.attachName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
    })
    .catch(() => {
      proxy.$modal.closeLoading();
    });

猜你喜欢

转载自blog.csdn.net/SunFlower914/article/details/132871880