uniapp uview上传图片 u-upload

uniapp uview上传图片 u-upload_第1张图片
示例:

<u-upload 
	:fileList="fileList" 
	multiple
	:maxCount="3" 
	:maxSize="10 * 1024 * 1024"
	@afterRead="afterRead"
	@delete="deletePic"
	@oversize="overSize"
>
</u-upload>
// 图片大小超出最大允许大小
overSize(e) {
	uni.$u.toast('上传图片大小不能超过10MB!')
},
// 删除图片
deletePic(event) {
	this.fileList.splice(event.index, 1)
},
// 新增图片
async afterRead(event) {
	// 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
	let lists = [].concat(event.file)
	let fileListLen = this.fileList.length
	lists.map((item) => {
		this.fileList.push({
			...item,
			status: 'uploading',
			message: '上传中'
		})
	})
	for (let i = 0; i < lists.length; i++) {
		const result = await this.uploadFilePromise(lists[i].url)
		let item = this.fileList[fileListLen]
		this.fileList.splice(fileListLen, 1, Object.assign(item, {
			status: result.status,
			message: result.status == 'failed' ? '上传失败' : '',
			url: result.url
		}))
		fileListLen ++
	}
},
uploadFilePromise(url) {
	const param = {
		filePath: url,
		type: 'images'
	}

	return new Promise((resolve, reject) => {
		uploadFiles(param).then(res => {
			if (res.code == 200) {
				resolve({
					url:res.data[0].showPath,
					status: 'success'
				})
			} else {
				resolve({
					url:url,
					status: 'failed'
				})
			} 
		})
	})
}

包含了三种状态success,failed,uploading,可用于提交表单时判断图片是否都上传成功

你可能感兴趣的:(javascript,前端,vue,uni-app,小程序)