base64下载文件,修改文件名

downLoad(){
let download=file_name;//下载名称
let b6=getBase64Type(this.file_type)+this.base64; //格式 file_type文件格式
let blob = dataURLToBlob(b6);
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
let fileName = download //放在response header里的fileName
let a = document.createElement('a');
a.download = decodeURI(fileName); //文件名
a.href = URL.createObjectURL(dataURLToBlob(e.target.result));
$("body").append(a); // 修复firefox中无法触发click
a.click();
$(a).remove();
this.pdfjx=0
}
},
dataURLToBlob(dataurl) {
let arr = dataurl.split(',');
//注意base64的最后面中括号和引号是不转译的
let _arr = arr[1].substring(0,arr[1].length-2);
let mime = arr[0].match(/:(.*?);/)[1],
bstr =atob(_arr),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
},
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,';
}
},
posted @ 2022-07-09 17:42  是闷闷啊  阅读(556)  评论(0编辑  收藏  举报