前端下载base64文件

205 阅读1分钟

场景:后端不返回文件流,返回base64格式的文件,此时应该怎么下载

  1. 获取base64前缀,如已返回,则不需要
getBase64Type (type) {
      switch (type) {
        case 'txt': return 'data:text/plain;base64,'
        case 'doc': return 'data:application/msword;base64,'
        case 'docx': return 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,'
        case 'xls': return 'data:application/vnd.ms-excel;base64,'
        case 'xlsx': return 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'
        case 'pdf': return 'data:application/pdf;base64,'
        case 'pptx': return 'data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,'
        case 'ppt': return 'data:application/vnd.ms-powerpoint;base64,'
        case 'png': return 'data:image/png;base64,'
        case 'jpg': return 'data:image/jpeg;base64,'
        case 'gif': return 'data:image/gif;base64,'
        case 'svg': return 'data:image/svg+xml;base64,'
        case 'ico': return 'data:image/x-icon;base64,'
        case 'bmp': return 'data:image/bmp;base64,'
      }
    },
  1. 拼接为完整的base64
let base64 = this.getBase64Type(res.data.fileType) + res.data.data
  1. 将完整的base64转为Blob
dataURLtoBlob (base64) {
      var arr = base64.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
},
  1. 将blob转为URL
let url = URL.createObjectURL(dataURLtoBlob(base64))
  1. 下载文件
  downloadFile (url, name = "默认文件名.txt") {
      var a = document.createElement("a")
      a.setAttribute("href", url)
      a.setAttribute("download", name)
      a.setAttribute("target", "_blank")
      let clickEvent = document.createEvent("MouseEvents")
      clickEvent.initEvent("click", true, true)
      a.dispatchEvent(clickEvent)
},