前端下载base64文件base64转blob
目录
前端下载base64文件;base64转blob
场景与思路:1.后端返回base64,可能包含或不包含前缀(自行拼接前缀即可)2.返回文件类型 3.返回文件名称
下载思路:
在方法dataURLtoBlob上,先将base64通过atob转成blob格式
再通过URL.createObjectURL()将blob读取出url地址
3.在使用a标签下载
//获取后端返回的不完成base64、文件名、文件类型
downladBase64 (item) {
MyGet(G_CGI_PHP.invoiceApi.mobileDownInvoiceBase64 + `?policyId=${item.id}`).then((res) => {
if (res.success) {
let base64 = this.getBase64Type(res.data.fileType) + res.data.data //类型拼接后端给的不完整base64
console.log('拼接完整的base64', base64)
this.downloadFileByBase64(base64, res.data.fileName)
} else {
}
})
},
//根据文件后缀 获取base64前缀不同 拼接完整的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,'
}
},
//将完整的base64转换为blob
dataURLtoBlob (dataurl) {
var arr = dataurl.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 })
},
// * desc: 下载参数入口
// * @param base64 :返回数据的blob对象或链接
// * @param fileName :下载后文件名标记
downloadFileByBase64 (base64, fileName) {
var myBlob = this.dataURLtoBlob(base64)
var myUrl = URL.createObjectURL(myBlob)
this.downloadFile(myUrl, fileName)
},
// * desc: 下载方法
// * @param url :返回数据的blob对象或链接
// * @param fileName :下载后文件名标记
downloadFile (url, name = "What's the fuvk") {
console.log('url==',url)
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)
},