我写技术文章没那么多废话,直接上代码:
1.在html里:
max-count是限制上传的数量
accept是限制上传文件的类型
<van-field name="Files" label="照片" >
<template #input>
<van-uploader :max-count="1" accept='.jpg,.jpeg,.png' v-model="data.photoUrl" :before-read="beforeRead" :after-read="afterRead" @delete="deleteFiles"/>
</template>
</van-field>
2.在ts里:
我是在before-read里限制上传文件类型、上传文件大小、图片的宽高
//(boolean | undefined | Promise<File | File[] | undefined>) 这个是防止:before-read报红
const beforeRead = (file:any, detail:any) : (boolean | undefined | Promise<File | File[] | undefined>) => {
console.log("上传前",file);
const imgformat = /image\/(png|jpg|jpeg)$/;
if (!imgformat.test(file.type)) {
Toast.fail('请上传 jpg/jpeg/png 格式图片');
return false;
}
if (file.size > 5 * 1024 * 1024) {
Toast.fail('文件大小不能超过 5M');
return false;
}
return new Promise((resolve) => {
//用这种方式是因为用到了vant3推荐的Compressor
Promise.all([checkWidthAndHeight(file)]).then(res => {
return new proxy.Compressor (file, {
success: resolve
})
})
})
};
//检查图片的宽高
const checkWidthAndHeight = (file:any) => {
return new Promise((resolve,reject) => {
var img = new Image();
img.src = URL.createObjectURL(file);
img.onload = function () {
var width = img.width;
var height = img.height;
console.log("当前图片的宽高", width, height);
if (width > 500 || height > 695) {
Toast.fail('图片分辨率不能超过 500 X 695'); // 图片分辨率不能超过 500 X 695
reject(false);
}else{
resolve(true);
}
}
})
}
//删除头像
const deleteFiles = (file: any, detail: any): void => {
console.log("删除数据",file,detail);
}
3.感谢
如果觉得写得好,记得收藏哦 ~ (O_O) ~