云开发批量上传图片,上传完图片再上传数据库 [即抄即用,拎包入住]
发布于 4 年前 作者 xialiu 3244 次浏览 来自 分享

大家好,又是我拎包哥,今天我们来实现在云开发中批量上传图片。

经过__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',
                filePaththis.TFP[i]
            }).then(res => {
                this.imgList.push(res.fileID)
            })
        }

        Promise.all([a]).then(res => {
            test.add({
                data: {
                    imgListthis.imgList
                }
            })
        })
    }
})

--------------------------------------我是分割线--------------------------------------

要点:

  1. ctrl c + ctrl v
  2. 这里用了await阻塞在wx.cloud.uploadFile前面,避免__还没上传完图片就__往数据库插入数组。减少了then里的代码,美观逼格高。嘻嘻嘻。
  3. 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=

9 回复

很好很好,感谢分享!

厉害了

--↓↓👍如果觉得有帮助的话请点个【赞】吧(唏嘘也有小尾巴了,可惜是假的)

往数据库插入的代码呢??

多张图片为啥不同时异步上传?减少等待时间

看后有收获,非常感谢分享。

厉害了

--↓↓👍如果觉得有帮助的话请点个【赞】吧(唏嘘也有小尾巴了,可惜是假的)

能帮我看看我的问题嘛,我的和你的内容有点像

666

<p style="display: tail;text-align: left;border-top: 0.5px solid rgba(0,0,0,.06);padding-top: 5px;margin-top: 15px;" title="tail"><span style="width: fit-content;background: linear-gradient(45deg, red, rgb(135, 230, 255), rgb(255, 135, 230));font-size: 10px;color: transparent;-webkit-background-clip: text;"><span title="尊贵的 SVVVIP 特权">--↓↓👍如果觉得有帮助的话请点个【赞】吧(唏嘘也有小尾巴了,可惜是假的)</span></span></p>

在CSDN找了好久没找到。。。🙏感谢

回到顶部