微信小程序多图上传

选择图片wx.chooseImage

微信小程序多图上传_第1张图片
微信小程序多图上传_第2张图片

上传图片wx.uploadFile

微信小程序多图上传_第3张图片

微信小程序多图上传_第4张图片


  1. 点击选择图片
chooseImg: function () {
    var that = this;
    var selectImg = that.data.selectImg;
    wx.chooseImage({
      count: 5,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        var tempFilePaths = res.tempFilePaths

        if (tempFilePaths.length + selectImg.length > 5) {
          that.tips('最多只能上传5张')
        } else {
          for (var i = 0; i < tempFilePaths.length; i++) {
            selectImg.push(tempFilePaths[i])
            // that.uploadImg(tempFilePaths[i])
          }
          that.setData({
            selectImg: selectImg
          })
          console.log(selectImg);
        }

      },
      fail: function () {
        that.tips('选取图片失败')
      }
    })
  },
  1. 提交表单,遍历selectImg ,调用uploadImg()进行图片一张张上传。
  2. 上传图片
uploadImg: function (img,fn){
    var that = this;
    var imgs = that.data.imgs;
    app.getLoginSession(function (session) {
      wx.uploadFile({
        url: app.api,
        filePath: img,
        name: 'file',
        formData: {
          app: 'farm',
          act:'upload_file',
          filePath: img,
          t_session: session
        },
        method: 'POST',
        header: {
          'content-type': 'multipart/form-data'
        },
        success: function (res) {
          var data = JSON.parse(res.data);
          var rlt = data.retval;
          if (data.done) {

            imgs.push(rlt.save_path);
            that.setData({
              imgs:imgs
            })
            console.log("sss"+that.data.imgs)
            typeof fn == 'function' && fn();
          } else {
            console.log(data);
            that.tips('图片上传失败')
          }
        },
        fail:function(){
          console.log("失败");
        }
      })
    })
  },

你可能感兴趣的:(微信小程序)