最近在做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; }
三、獲取圖片接口數據格式