Js转文件为Base64和Js下载Base64文件

非常的好用!

js转文件为base64字符串

1
2
3
4
5
6
7
8
function fileToBase64(file, callback) {
let reader = new FileReader();
reader.addEventListener('load', (e) => {
callback(e.target.result);
reader = null;
});
reader.readAsDataURL(file);
}

竟然还有童鞋不知道咋上传文件,下面封装了一下,直接调用pickerFileBase64这个函数就可以选取文件并且得到base64字符串了

用例:纯Js获取文件并转base64

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function pickerFileBase64() {
return new Promise((resolve) => {
const inputFile = document.createElement('input')
inputFile.type = 'file'
inputFile.onchange = event => {
const file = event.target.files[0]
function fileToBase64(file, callback) {
const reader = new FileReader();
reader.addEventListener('load', (e) => {
callback(e.target.result);
reader = null;
});
reader.readAsDataURL(file);
}
fileToBase64(file, resolve)
}
inputFile.click()
})
}

(async () => {
const base64 = await pickerFileBase64()
console.log(base64)
})()

下载base64字符串文件也是非常简单的,直接调用就完事了

js下载base64字符串文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function downloadBase64File(base64,name){
function 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 });
}

function downloadFile(url,name=new Date().toLocaleString()){
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);
}
var myBlob = dataURLtoBlob(base64)
var myUrl = URL.createObjectURL(myBlob)
downloadFile(myUrl,name)
}

作者

vear

发布于

2022-01-12

更新于

2022-01-18

许可协议

评论