云开发批量上传图片,上传完图片再上传数据库 [即抄即用,拎包入住]
大家好,又是我拎包哥,今天我们来实现在云开发中批量上传图片。
经过__Stephen__哥的指正,我改用了Promise.all的方法来达到目的。
Promise.all的作用就是等待所包含的promise函数结束后再执行下一步逻辑,非常方便好用!
const db = wx.cloud.database()
const test = db.collection('test')
Page({
onLoad() {
this.imgList = []
wx.chooseImage({
success: (res) => {
this.TFP = res.tempFilePaths
}
})
},
btn() {
this.imgList = []
for (let i = 0; i < this.TFP.length; i++) {
var a = wx.cloud.uploadFile({
cloudPath: 'img' + i + '.png',
filePath: this.TFP[i]
}).then(res => {
this.imgList.push(res.fileID)
})
}
Promise.all([a]).then(res => {
test.add({
data: {
imgList: this.imgList
}
})
})
}
})
--------------------------------------我是分割线--------------------------------------
要点:
- ctrl c + ctrl v
- 这里用了await阻塞在wx.cloud.uploadFile前面,避免__还没上传完图片就__往数据库插入数组。减少了then里的代码,美观逼格高。嘻嘻嘻。
- await wx.cloud.uploadFile不能放在wx.chooseImage里,如果可以的话,请告诉我怎么做,谢谢!
欢迎交流,指出错误,我立刻修改么么哒。
async await
btn
--------------------------------------------------
const db = wx.cloud.database()
const test = db.collection('test')
Page({
onLoad() {
this.imgList = []
wx.chooseImage({
success: (res) => {
this.TFP = res.tempFilePaths
}
})
},
async btn() {
this.imgList = []
console.log(this.TFP)
for (let i = 0; i < this.TFP.length; i++) {
await wx.cloud.uploadFile({
cloudPath: 'img' + i + '.png',
filePath: this.TFP[i]
}).then(res => {
this.imgList.push(res.fileID)
})
}
test.add({
data: {
imgList: this.imgList
}
})
}
})
=v=
