js base64 轉(zhuǎn)文件,下載到本地

// * desc: base64對象轉(zhuǎn)blob文件對象
// * @param urlData  :數(shù)據(jù)的base64對象
// * @param type  :類型
// * @returns {Blob}:Blob文件對象
base64ToBlob(urlData, type) {
  const arr = urlData.split(',')
  const array = arr[0].match(/:(.*?);/)
  const mime = (array && array.length > 1 ? array[1] : type) || type
  // 去掉url的頭,并轉(zhuǎn)化為byte
  const bytes = window.atob(arr[1])
  // 處理異常,將ascii碼小于0的轉(zhuǎn)換為大于0
  const ab = new ArrayBuffer(bytes.length)
  // 生成視圖(直接針對內(nèi)存):8位無符號整數(shù),長度1個字節(jié)
  const ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], {
    type: mime
  })
},

// * desc: 下載導(dǎo)出文件
// * @param blob  :返回數(shù)據(jù)的blob對象或鏈接
// * @param fileName  :下載后文件名標記
// * @param fileType  :文件類 word(docx) excel(xlsx) ppt等
downloadExportFile(blob, fileName, fileType) {
  const downloadElement = document.createElement('a')
  let href = blob
  if (typeof blob === 'string') {
    downloadElement.target = '_blank'
  } else {
    href = window.URL.createObjectURL(blob) // 創(chuàng)建下載的鏈接
  }
  downloadElement.href = href
  downloadElement.download = fileName + '.' + fileType // 下載后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 觸發(fā)點擊下載
  document.body.removeChild(downloadElement) // 下載完成移除元素
  if (typeof blob !== 'string') {
    window.URL.revokeObjectURL(href) // 釋放掉blob對象
  }
},
// * desc: base64轉(zhuǎn)文件并下載
// * @param base64 {String} : base64數(shù)據(jù)
// * @param fileType {String} : 要導(dǎo)出的文件類型png,pdf,doc,mp3等
// * @param fileName {String} : 文件名
downloadFile(base64, fileName, fileType) {
  const typeHeader = 'data:application/' + fileType + ';base64,' // 定義base64 頭部文件類型
  const converedBase64 = typeHeader + base64 // 拼接最終的base64
  const blob = this.base64ToBlob(converedBase64, fileType) // 轉(zhuǎn)成blob對象
  this.downloadExportFile(blob, fileName, fileType) // 下載文件
}

使用:

this.downloadFile('你的base64數(shù)據(jù)','你的文件名稱','你的文件數(shù)據(jù)類型');
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。