小程序开发-多图上传

        我在用uniapp开发小程序的时候发现一个问题。使用图片上传功能的时候,小程序无法使用uni.uploadFile内的files字段一次性上传多张图片;只能循环一张一张图片上传;那么就涉及一个问题,循环上传过程中可能第一张图片已经上传好了,但后续的图片还没有上传完成;这时候结束页面的加载状态会出现图片不完全显示的问题。

  解决方案:使用Promise.all,待所有上传完成后再进入then函数,关闭页面的加载状态。

  话不多说,上代码:(写在一个js文件里)

// 多图上传 使用promise.all .js文件
// 传入参数:count:最大图片数;successcc:成功后调用的函数,failcc:失败后调用的函数

    uploadImgs(count, successcc, failcc) {
        uni.chooseImage({
            count: count,
            fail(err) {
                if (err.errCode == 0) {
                    uni.showModal({
                        title: "提示",
                        content: "您暂未允许应用读写设备上的照片及文件,请前往设置-应用权限开启该权限"
                    })
                    return
                }
                if (err.errMsg.includes('No Permission')) {
                    uni.showModal({
                        title: "提示",
                        content: "您暂未允许应用拍摄与录制,请前往设置-应用权限开启该权限"
                    })
                    return
                }
            },
            success(files) {
                console.log("数据", files)
                uni.showLoading({
                    title: "图片上传中",
                    mask:true
                })
                Promise.all(files.tempFilePaths.map(itm => uploadF(itm))).then(res => {
                    console.log(res, 'promise')
                    successcc && successcc(res)
                }).catch(err => {
                    console.log(err, 'promise')
                    failcc && failcc(err)
                })
            }
        })

        function uploadF(filepath) {
            return new Promise((resolve, reject) => {
                wx.uploadFile({
                    filePath: filepath,
                    name: 'file',
                    url: HTTP_REQUEST_URL + '/staffapi/upload/image',
                    success(res) {
                        resolve(res.data);
                    },
                    fail(msg) {
                        reject();
                    }
                })
            });
        }
    },

  页面中的调用:(vue页面调用)

this.$util.uploadImgs(count, (res) => {
      uni.hideLoading()
           console.log(res,'promise back')
           _this.formdata.ss_array[index].ss_img = res
     }, (err) => {
         uni.showToast({
           title: "图片上传失败,单图最大不能超过10M",
           icon: "none"
       })
})

  这样的话Promise.all就会在执行了所有函数后再返回,图片就会一次性全部加载出来;但是会加大用户的等待时间。

  如果是使用微信开发者工具来开发小程序,这一部分也是一样的,只需要将uni. 改成wx. 即可

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值