Vant Uploader uploads multiple pictures and sets status

Uploader multiple uploads, use file.status to set the upload status

1. Page structure

<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. Put the preconditions in the beforeRaed method (whether it is a picture type, whether it exceeds the limited file size)

After judging whether the file meets the conditions in the beforeRead method, you must remember to return true or false status, otherwise the afterRead method will not be executed. Very important! ! ! !

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. Set upload status and upload prompt in 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. After calling the API to upload successfully, set the status to success

About compressFile() is a method of image compression. It is written in another article of mine. If you are interested, you can take a look. Vue image upload compression is attached to the portal (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("照片上传失败,请重新上传!")
	})
}

At this point, the process of uploading files and setting upload status is complete!

over~

Guess you like

Origin blog.csdn.net/codingLeader/article/details/123656613