Download and preview files in base64 format (pdf/word/ppt, etc.)

 

 The backend returns file data in base64 format, and the frontend converts the received data to implement the download and preview method of the file:

// 附件下载  这里的的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(() => {});
};

Guess you like

Origin blog.csdn.net/SunFlower914/article/details/130192766