# file转base64
// file转base64
const getBase64=function(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
let fileResult = "";
reader.readAsDataURL(file);
//开始转
reader.onload = function () {
//这里其实就是需要的base64格式了
let Result = reader.result;
//base64数据去头
let head = Result.indexOf("4") + 2;
fileResult = Result.substring(head, Result.length - head);
};
//转 失败
reader.onerror = function (error) {
reject(error);
};
//转 结束 咱就 resolve 出去
reader.onloadend = function () {
resolve(fileResult);
};
});
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# base64转file
// base64转file
const dataURLtoFile=function(dataurl, filename) {
let arr = `data:image/png;base64,${dataurl}`.split(",")
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = window.atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// 如果需要指定格式可以设置type,如 type: "application/vnd.ms-excel" 表示excel格式blob ;默认为 type: mime 按 MIME 规范编码.
const blob = new File([u8arr], filename || "file", { type: mime });
// 如果不需要 formdata 包装,上一步就可以了
let params = new FormData();
params.append("file", blob);
return params;
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# base64转blob
//base64转blob
const base64ToBlob = function(base64Data) {
let file = window.atob(fileData.fileData);
let len = file.length
// 创建一个存储解码后数据的数组
let arr = new Uint8Array(len);
// blob只能接收二进制编码,需要讲base64转为二进制再塞进去
for (var i = 0; i < len; i++) {
arr[i] = file.charCodeAt(i);
}
let blob = new Blob([arr], {
type: "application/vnd.ms-excel"
});
return blob
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# blob转base64
//blob转base64
const blobToBase64=function(blob) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
resolve(e.target.result);
};
// readAsDataURL
fileReader.readAsDataURL(blob);
fileReader.onerror = () => {
reject(new Error('blobToBase64 error'));
};
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# blob转file
const blobToFile=function(blob){
return new File([blob], 'name.wav', {type: 'audio/wav'});
}
1
2
3
2
3
# blob转blobUrl
const blobToBlobUrl=function(blob){
window.URL = window.URL || window.webkitURL;
return window.URL.createObjectURL(blob);
}
1
2
3
4
2
3
4
# file转blob
const flieToBlob=function(file){
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
resolve(new Blob([e.target.result], { type: file.type }));
};
// readAsDataURL
fileReader.readAsDataURL(file);
fileReader.onerror = () => {
reject(new Error('flieToBlob error'));
};
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13