上传头像为例子
base64转换为file类型
点击头像,选择文件
点击选取时,获取base64文件
这里使用了Vue-ImgCut插件
代码解析
function base64toFile(dataurl, filename = "file") {
let arr = dataurl.split(",")
}
console.log(arr) 👇
let mime = arr[0].match(/:(.*?);/)[1];
console.log(mime) 👇
console.log(arr[0].match(/:(.*?);/))👇
let suffix = mime.split("/")[1];
let bstr = atob(arr[1]);
console.log(bstr) 👇
let n = bstr.length;
let u8arr = new Uint8Array(n);
console.log(n) 👇
console.log(u8arr) 👇
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
console.log(bstr.charCodeAt(n)) 👇
console.log([u8arr]) 👇
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
完整代码如下
function base64toFile(dataurl, filename = "file") {
let arr = dataurl.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let suffix = mime.split("/")[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
});
}
post 请求发过去到服务器时: