base64格式(pdf/word/ppt等)文件的下载与预览

 

 后端返回base64格式的文件数据,前端根据接收的数据进行转换后实现对文件的下载和预览方法:

// 附件下载  这里的的data就是content数据
const downloadAttach = (id) => {
  downloadAttachment({ attachmentId: id })
    .then(({ data }) => {
      const raw = window.atob(data.content);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      const blob = new Blob([uInt8Array], { type: data.contentType });

      // 下载方法
      const elink = document.createElement("a");
      elink.download = data.attachName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();

      // 预览方法
      window.open(URL.createObjectURL(blob))
    })
    .catch(() => {});
};

猜你喜欢

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