最近在做vant图片上传,简单记录下,很多东西还待完善
因为我这个是编辑图片后最后和表单数据一起用ajax进行保存的,所以用两个数组来保存新增的图片和删除的图片
newImg:新增图片
delImg:删除图片
一、使用<van-uploader>进行图片上传
<van-field :name="item.name" :label="item.label"> <template #input> <van-uploader v-model="dataList[item.name].value" multiple :max-count=maxImgCount :after-read="onRead" :before-delete="delImgs" /> </template>
</van-field>
<script>
export default {
data() {
return {
name:‘‘,
}
},
methods: {
onRead(file,name) {
if (file instanceof Array && file.length) { // 判断是否是多图上传 多图则循环添加进去
file.forEach(item => {
this.newImg[name.index] = item;
})
} else {
this.newImg[name.index] = file;
}
},
/*点击删除图片*/
delImgs(file, name) {
if(isNotNull(file.url))
{
this.delImg.push(file.url);
}else{
this.newImg.splice(name.index, 1);
}
this.dataList[‘imagename‘].value.splice(name.index, 1);
},
}
}
</script>
//ajax保存的时候循环下文件
this.dataList.imagedel = this.delImg;
if(isNotNull(this.newImg))
{
this.dataList.imagename=‘‘;
for (var imageitem in this.newImg) {
imagelist[‘content‘]=this.newImg[imageitem].content;
imagelist[‘imagename‘]=this.newImg[imageitem].file.name;
imagelist[‘imagetype‘]=this.newImg[imageitem].file.type;
imagelist[‘imagesize‘]=this.newImg[imageitem].file.size;
this.dataList.imagedata.push(imagelist);
}
}
二、后台处理base64图片上传
function uploadBase64Image($img,$current_id,$binFile,$upload_file_path) { if (preg_match(‘/^(data:\s*image\/(\w+);base64,)/‘, $img, $result)) { // $type = ".".$result[2]; $path = $upload_file_path .$current_id . "_" . $binFile; } $img = base64_decode(str_replace($result[1], ‘‘, $img)); @file_put_contents($path, $img); return $path; }
三、获取图片接口数据格式