我写技术文章没那么多废话,直接上代码:
1.在html里:
<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里:
观察上传时,van-uploader返回的file,上面这种结构是能够正常回显的,那么我们要做的就是构建这种结构:
// 将base64转换为blob转为file
const dataURLtoBlobtoFile = (dataurl:any) =>{
var arr = dataurl.split(',')
var mime = arr[0].match(/:(.*?);/)[1]
var bstr = atob(arr[1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
// return new Blob([u8arr], { type: mime })
let theBlob:any = new Blob([u8arr], { type: mime });
theBlob.lastModifiedDate = new Date()
theBlob.name = "预览图片"
return theBlob;
}
//调用获取图片接口
const showPhoto = () =>{
getPhoto().then((res: any) => {
if (res.code === '0') {
if(res.data) {
//这是接口获得base64
data.photoUrl = [{ content:res.data,file:dataURLtoBlobtoFile(res.data)}]
}
} else Toast.fail(res.messege)
})
}
此种方法就不需要另外引用那个ImagePreview ,直接就能实现回显