收藏
回答

怎么解决多图上传服务器成功后返回的图片id逐一赋给图片?

在本人瞎想到的方法里,到最后一步将返回的id赋给页面属性时不是undefined就是统一设置成最后一张图返回的id。。。求大神们帮解决一下。看下图:





回答关注问题邀请回答
收藏

3 个回答

  • SHIELD
    SHIELD
    2018-08-16

    楼主可以参考下,采用的递归上传,这样能保证顺序性,页面上用的是progressArray循环展示图片,支持上传进度条:

    const defaultProgress = {
      uploading: false,
      progressShow: false,
      progress: 0,
      url: '',
      task: {}
    };
    const defaultApply = {
      id: null,
      sex: 2,
      post: 1,
      onPost: true,
      inspectedRealName: '',
      reason: '',
      imageId: '',
      imageIdArray: [],
      jobImage: '',
      jobImageArray: [],
      progressArray: []
    };
     
      //上传图片
      chooseImageClick: function (e) {
        console.info('[chooseImageClick]----->', e);
        let that = this;
        that.setData({
          stageBtnDisabled: true,
          submitBtnDisabled: true
        });
        wx.getLocation({
          success: function (location_res) {
            console.info('[wx.getLocation success]----->', location_res);
            wx.chooseImage({
              sizeType: ['compressed'],
              sourceType: ['camera'],
              success: function (image_res) {
                console.info('[wx.chooseImage success]----->', image_res);
                var filePaths = image_res.tempFilePaths;
                var formData = {
                  folder: 'patrol',
                  longitude: location_res.longitude,
                  latitude: location_res.latitude
                };
                that.judgePrevFile(filePaths, 0, formData);
                //that.recursionUploadFile(filePaths, 0, formData);
                that.setData({
                  stageBtnDisabled: false,
                  submitBtnDisabled: false
                });
              },
              fail: function (image_res) {
                console.info('[wx.chooseImage fail]----->', image_res);
                if (image_res.errMsg == 'chooseImage:fail auth deny'
                    || image_res.errMsg == 'chooseImage:fail:auth denied') {
                  app.checkAuthorization({});
                }
                that.setData({
                  stageBtnDisabled: false,
                  submitBtnDisabled: false
                });
              }
            });
          },
          fail: function (location_res) {
            console.info('[wx.getLocation fail]----->', location_res);
            if (location_res.errMsg == 'getLocation:fail auth deny'
                || location_res.errMsg == 'getLocation:fail:auth denied') {
              app.checkAuthorization({});
            }
            that.setData({
              stageBtnDisabled: false,
              submitBtnDisabled: false
            });
          }
        });
      },
     
      //判断上一个文件是否完成上传
      judgePrevFile: function (filePaths, current, formData) {
        console.info('[judgePrevFile]----->', current);
        var that = this;
        var progressArray = that.data.empJobApply.progressArray;
        if (progressArray.length > 0 && progressArray[progressArray.length - 1].url === '') {
          setTimeout(function () {
            that.judgePrevFile(filePaths, current, formData);
          }, 500);
        } else {
          that.recursionUploadFile(filePaths, current, formData);
        }
      },
     
      //递归上传文件
      recursionUploadFile: function (filePaths, current, formData) {
        console.info('[recursionUploadFile]----->', current);
        console.info('[recursionUploadFile]----->', '开始上传第' + (current + 1) + '个文件');
        var that = this;
        var apply = that.data.empJobApply;
        apply.progressArray.push(Object.assign({}, defaultProgress, {uploading: true, progressShow: true}));
        that.setData({
          empJobApply: apply
        });
     
        var uploadTask = tt.upload({
          url: '/image/upload/single',
          filePath: filePaths[current],
          name: 'image_file',
          formData: formData,
          success: upload_res => {
            console.info('[recursionUploadFile success]----->', upload_res);
            if (upload_res.statusCode && upload_res.statusCode == 413) {
              wx.showToast({title: '文件太大啦!', image: '../../utils/imgs/error-150.png', duration: 3000});
              apply.progressArray.splice(apply.progressArray.length - 1, 1);
              that.setData({
                empJobApply: apply
              });
              return;
            }
            var data = JSON.parse(upload_res.data);
            if (data.status && data.status == 500) {
              wx.showToast({title: '上传出错啦!', image: '../../utils/imgs/error-150.png', duration: 3000});
              apply.progressArray.splice(apply.progressArray.length - 1, 1);
              that.setData({
                empJobApply: apply
              });
              return;
            }
            if (data.suc) {
              apply.imageIdArray.push(data.ext.imageId);
              apply.jobImageArray.push(data.info);
              apply.imageId = apply.imageIdArray.join(',');
              apply.jobImage = apply.jobImageArray.join(',');
              apply.progressArray[apply.progressArray.length - 1].url = data.info;
              apply.progressArray[apply.progressArray.length - 1].uploading = false;
              apply.progressArray[apply.progressArray.length - 1].progressShow = false;
              //wx.showToast({ title: '上传成功!', image: '../../utils/imgs/success-150.png', duration: 3000 });
            } else {
              wx.showToast({title: data.msg, icon: 'none', duration: 3000});
              apply.progressArray.splice(apply.progressArray.length - 1, 1);
            }
            that.setData({
              empJobApply: apply
            });
          },
          fail: upload_res => {
            console.info('[recursionUploadFile fail]----->', upload_res);
            if (upload_res.errMsg == 'uploadFile:fail abort') {
              wx.showToast({
                title: '已取消上传',
                icon: 'none',
                duration: 1500
              });
            } else {
              wx.showToast({
                title: '上传失败!',
                image: '../../utils/imgs/error-150.png',
                duration: 1500
              });
            }
     
            apply.progressArray.splice(apply.progressArray.length - 1, 1);
            that.setData({
              empJobApply: apply
            });
          },
          complete: upload_res => {
            console.info('[recursionUploadFile complete]----->', upload_res);
            if ((current + 1) === filePaths.length) return;
            that.recursionUploadFile(filePaths, ++current, formData);
          }
        });
        apply.progressArray[apply.progressArray.length - 1].task = uploadTask;
        that.setData({
          empJobApply: apply
        });
        //监听上传进度
        uploadTask.onProgressUpdate((progress_res) => {
          apply.progressArray[apply.progressArray.length - 1].progress = progress_res.progress;
          that.setData({
            empJobApply: apply
          });
          console.log('[上传进度]----->', progress_res.progress);
          console.log('[已经上传的数据长度]----->', progress_res.totalBytesSent);
          console.log('[预期需要上传的数据总长度]----->', progress_res.totalBytesExpectedToSend);
        });
        //取消上传任务
        //uploadTask.abort();
      },
     
      //删除上传图片
      deleteImage: function (e) {
        console.info('[deleteImage]----->', e);
        var that = this;
        var ploopIndex = e.currentTarget.dataset.ploopindex;
        var apply = that.data.empJobApply;
        apply.imageIdArray.splice(ploopIndex, 1);
        apply.jobImageArray.splice(ploopIndex, 1);
        apply.imageId = apply.imageIdArray.join(',');
        apply.jobImage = apply.jobImageArray.join(',');
        if (apply.progressArray[ploopIndex] && apply.progressArray[ploopIndex].uploading) {
          apply.progressArray[ploopIndex].task.abort();
        } else {
          apply.progressArray.splice(ploopIndex, 1);
        }
        that.setData({
          empJobApply: apply
        });
      },


    2018-08-16
    有用 2
    回复
  • 卢霄霄
    卢霄霄
    2018-08-14

    用个list专门来存id?然后显示 data-id="{{list[index]}}"

    2018-08-14
    有用 1
    回复 20
    • ·R
      ·R
      2018-08-14

      本人刚接触小程序没多久,不知道还可以这样写的。。。能说详细点吗?谢谢了

      2018-08-14
      回复
    • 卢霄霄
      卢霄霄
      2018-08-14回复·R

      比如,你存id的array叫做 idList,然后在你每张图片上传成功的时候,就把返回的id放到idList对应的位置,比如,第一场图上传成功的方法里,把返回的id放到 this.data.idList[0] = id ;that.setData({idList:this.data.idList})。界面上你绑定 data-id的地方就改成 data-id="{{idList[index]}}"

      2018-08-14
      回复
    • ·R
      ·R
      2018-08-14回复卢霄霄


      是这样?是不是我data{ idList:[] }这样设置不对,图里的代码中idList是undefined的。。。

      2018-08-14
      回复
    • 卢霄霄
      卢霄霄
      2018-08-14回复·R

      that.setData({

      idList: this.data.idList

      })

      2018-08-14
      回复
    • ·R
      ·R
      2018-08-14回复卢霄霄

      现在不是这里的问题,idList一直是undefined。。。


      2018-08-14
      回复
    查看更多(15)
  • 7克
    7克
    2020-03-20

    使用该方法突破限制实现多图并发上传,顺序可控,案例参考:https://blog.songdonghong.com/2020/03/18/wxxcxplsc/

    2020-03-20
    有用
    回复
登录 后发表内容