Uploader多张上传,使用file.status设置上传状态
1、页面结构
<van-uploader :before-read="beforeRead" :after-read="afterRead" :before-delete="deletImg"
:max-count="maxSize" v-model="fileList" multiple>
<van-icon name="plus" />
</van-uploader>
2、前置条件放到beforeRaed方法中 (是否是图片类型、是否超过限定文件大小)
在beforeRead方法中判断文件是否符合条件后,一定要记得返回true或者false状态,不然afterRead方法不会执行。很重要!!!!
beforeRead(file) {
let This = this
if (Array.isArray(file)) {
if (file.length > This.maxSize) {
This.$toast("超过最大上传张数!")
return false
}
file.forEach(item => {
if (!item.type.startsWith('image')){
this.$toast("请上传图片!")
return false
}else if(item.size > 10485760){
this.$toast("图片超过10M!")
return false
}
})
} else {
if (!file.type.startsWith('image')){
this.$toast("请上传图片!")
return false
}
if(file.size > 10485760){
this.$toast("图片超过10M!")
return false
}
}
return true
},
3、在afterRaed中设置上传状态、上传提示语
afterRead(file) {
let This = this
if(Array.isArray(file)){
file.forEach(item => {
item.status = 'uploading'
item.message = '上传中...'
This.uploadMaterialImg(item)
})
}else {
file.status = 'uploading'
file.message = '上传中...'
this.uploadMaterialImg(file)
}
}
4、调用接口上传成功后,将状态设置为成功
关于compressFile()是图片压缩的方法,在我的另一篇文章中有写到,感兴趣可以看看,传送门附上vue 图片上传压缩(vue+Vant+image-compressor)
async uploadMaterialImg(imgFile) {
let This = this
let file = await this.compressFile(imgFile)
let formData = new FormData()
formData.append('file', file, file.name)
uploadMaterial(formData).then(res => {
if (res.code == 200) {
imgFile.status = 'done'
imgFile.message = '上传成功'
} else {
This.$toast("照片上传失败,请重新上传!")
}
}).catch(error => {
imgFile.status = 'failed'
imgFile.message = '上传失败'
This.$toast("照片上传失败,请重新上传!")
})
}
到此,上传文件设置上传状态的路程完毕!
完~