data:[<mediatype>][;base64],<data>
<img alt="logo" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...">
代码如下(示例):
<!--个人图片上传-->
<van-field name="pic" label="个人图片" required>
<template #input>
<van-uploader
v-model="headpic"
max-count="1"
accept="image/*"
:before-read="beforeRead"
:after-read="afterRead"
/>
</template>
</van-field>
上传前置处理(before-read)
beforeRead(file) {
if (file.type !== "image/jpeg") {
this.$toast("请上传jpg格式图片");
return false;
}
return true;
},
上传前置处理(after-read)
afterRead(file) {
console.log(file);//图片对象
this.$toast.loading("识别中");
if (file.file.size > 1024 * 1024) {
// 生成canvas
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
let img = new Image();
// 指定图片的DataURL(图片的base64编码数据)
img.src = file.content;
console.log(img.src);
img.onload = () => {
//画布大小
let w = canvas.width;
let h = canvas.height;
context.drawImage(img, 0, 0, w, h);
file.content = canvas.toDataURL(file.file.type, 1);
console.log(file.content);
// replace消除前缀,获取完整的base64码
// this.outForm.facep[0]=file.content.replace(/^data:image\/\w+;base64,/, '')
this.outForm.facep = file.content;
};
} else {
this.outForm.facep = file.content;
console.log(file);//查看未压缩的图片对象
}
}
//base64转图
var base64Img = result.data;//后端传回来的数据
var imgFile = this.base64ImgtoFile(base64Img);
// console.log(imgFile);//base64把图片转成文件对象
//把base64转file
base64ImgtoFile(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,
});
},
//获取个人头像
async getFacePicture() {
let param = {
picname: this.outForm.facep,
};
const result = await this.$service.getFacePicture(param);
if (result.code === 1) {
console.log(result.data);//后端返回base64
// Uploader 根据文件后缀来判断是否为图片文件
// 如果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明是否为一个图片
this.headpic.push({url:"result.data", isImage: true})//回填
}
},