示例:
<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,可用于提交表单时判断图片是否都上传成功