// * desc: base64對(duì)象轉(zhuǎn)blob文件對(duì)象
// * @param urlData :數(shù)據(jù)的base64對(duì)象
// * @param type :類型
// * @returns {Blob}:Blob文件對(duì)象
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)
// 生成視圖(直接針對(duì)內(nèi)存):8位無符號(hào)整數(shù),長(zhǎng)度1個(gè)字節(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 :返回?cái)?shù)據(jù)的blob對(duì)象或鏈接
// * @param fileName :下載后文件名標(biāo)記
// * @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ā)點(diǎn)擊下載
document.body.removeChild(downloadElement) // 下載完成移除元素
if (typeof blob !== 'string') {
window.URL.revokeObjectURL(href) // 釋放掉blob對(duì)象
}
},
// * 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對(duì)象
this.downloadExportFile(blob, fileName, fileType) // 下載文件
}
使用:
this.downloadFile('你的base64數(shù)據(jù)','你的文件名稱','你的文件數(shù)據(jù)類型');