微信小程序上传多个图片源码

开发小程序,如果 除了图片外,还有其他几个文本表单,想着一起上传,微信小程序只能先把图片给传上去,然后再提交表单了。如果上传多张图片,是采用循环上传图片的方式。

const uploadFile = (filePath, clear = false, fullPath = false) => {
  return new Promise((resolve, reject) => {
    getEnv().then((res) => {
      if (!filePath || filePath.length < 9) {
        wx.showModal({
          title: '图片错误',
          content: '请重试',
          showCancel: false,
        })
        return;
      }
      const fileType = '.' + filePath.split('.')[filePath.split('.').length - 1]
      const aliyunFileKey = res.dir + new Date().getTime() + Math.floor(Math.random() * 150) + fileType;
      const aliyunServerURL = res.host;
      const accessid = res.accessId;
      wx.uploadFile({
        url: aliyunServerURL, //开发者服务器 url
        filePath: filePath, //要上传文件资源的路径
        name: 'file', //必须填file
        formData: {
          'key': aliyunFileKey,
          'policy': res.policy,
          'OSSAccessKeyId': accessid,
          'signature': res.signature,
          'success_action_status': '200',
        },
        success: function (res) {
          if (res.statusCode != 200) {
            reject();
          }
          if (clear) {
            clearEnv()
          }
          if (fullPath)
            resolve(aliyunServerURL + '/' + aliyunFileKey) // 全路径上传
          else
            resolve(aliyunFileKey) // 残路径上传
        },
        fail: function (err) {
          err.wxaddinfo = aliyunServerURL;
          failc(err);
        },
      })
    })

  })

}
// 上传图片
  upload(imageList, imageSrcList = []) {
    let that = this
    if (imageSrcList == []) {
      imageList.forEach(() => {
        imageSrcList.push([])
      })
    }
    let clear = (times == imageList.length - 1)
    uploadImage(imageList[times], clear).then((result) => {
      wx.hideLoading();
      times++
      wx.showLoading({
        title: times + '/' + imageList.length
      })
      imageSrcList[times - 1] = result
      if (times == imageList.length) {
        times = 0
        that.addPhoto(imageSrcList)
      } else {
        that.upload(imageList, imageSrcList)
      }
    })
  },

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注