【小程序】一次最多选择9张,多张图片递归上传

需求

一次最多选择9张,多张图片递归上传。

思路

  1. 选择完图片,以递归的方式通过wx.uploadFile上传图片。
  2. 回显缩略图。

代码实现

步骤一

上传组件中的uploadOneByOne方法传入选择的图片列表,一张张的通过wx.uploadFile上传到微信服务器。

    /**
     * 附件上传
     */
    onUpload: function () {
      let currentPage = this;
      wx.chooseMedia({
        count: 9,
        mediaType: ["image"],
        sourceType: ["album", "camera"],
        sizeType: ["compressed"],
        camera: "back",
        success(res) {
          for (let i = 0; i < res.tempFiles.length; i++) {
            const item = res.tempFiles[i];
            if (item.size == 0 || item.size > 30000000) {
              ui.showToast("上传文件大小超过限制", 1000, "none");
              return;
            }
          }
          let successUp = 0; //成功
          let failUp = 0; //失败
          let count = 0; //第几张
          let length = res.tempFiles.length; //总数
          let list = [];
          currentPage.uploadOneByOne(
            res.tempFiles,
            list,
            successUp,
            failUp,
            count,
            length
          );
        },
      });
    },
    /**
     * 附件删除
     */
    onDelete: function (e) {
      let currentPage = this;
      let { index } = e.currentTarget.dataset;
      currentPage.triggerEvent("deleteevent", {
        onDelete: true,
        fileIndex: index,
      });
    },
    /**
     * 上传图片:以递归的方式上传
     * imgPaths:上传的图片列表
     * fileList:上传成功后返回的文件信息
     * successUp:上传成功的个数,初始化为0
     * failUp:上传失败的个数,初始化为0
     * count:第几张
     * length:图片列表的长度
     */
    uploadOneByOne(imgPaths, fileList, successUp, failUp, count, length) {
      let that = this;
      let imgPath = imgPaths[count].tempFilePath;
      let index = imgPath.lastIndexOf("/");
      let filename = imgPath.substring(index + 1, imgPath.length);
      let data = new FormData().getData();
      wx.uploadFile({
        url: `${app.globalData.baseUrl}/file/upload`,
        filePath: imgPath,
        name: "file",
        header: {
          Authorization: "Bearer " + that.data.access_token,
          "content-type": data.contentType,
        },
        formData: {
          filename: filename,
        },
        success: function (e) {
          // 坑:与wx.request不同的是,upload返回的是字符串格式,需要字符串对象化
          const file = JSON.parse(e.data);
          if (e.statusCode == 200) {
            fileList.push({ onSuccess: true, file: file.data, filename });
            successUp++; //成功+1
          }
        },
        fail: function (e) {
          console.log(e, "上传失败");
          failUp++; //失败+1
        },
        complete: function (e) {
          count++; //下一张
          if (count == length) {
            //上传完毕,作一下提示
            ui.showToast(
              `上传成功 ${successUp} 张,失败 ${failUp}`,
              1000,
              "none"
            );
            that.triggerEvent("successevent", {
              onSuccess: true,
              files: fileList,
            });
          } else {
            //递归调用,上传下一张
            that.uploadOneByOne(
              imgPaths,
              fileList,
              successUp,
              failUp,
              count,
              length
            );
          }
        },
      });
    },

步骤二

在使用到组件的页面进行附件上传成功、附件删除成功后的回调处理。
上传微信服务器成功后,才开始进行真正的上传服务器操作。这里需要注意要异步请求、异步更新附件信息关联对应的订单类型。

  /**
   * 附件上传、删除成功后的回调
   * 指定索引更新缩略图 未做
   */
  updateFile: function (e) {
    let currentPage = this;
    let { onDelete, onSuccess, fileIndex, files } = e.detail;
    let { loscamOrderId } = currentPage.data.form;
    let tableType = "pallet_issue";
    let list = currentPage.data.fileList;
    if (onSuccess) {
      for (let i = 0; i < files.length; i++) {
        const ele = files[i];
        let file = {
          ...ele.file,
          name: ele.filename,
          filename: ele.filename,
          tableType: tableType,
          url: `${app.globalData.baseUrl}/file/downloadfile?fileUrl=${ele.objectId}`,
        };
        list.push(file);
      }
      if (loscamOrderId) {
        currentPage.updateFileById(tableType, list, loscamOrderId);
      } else {
        list.forEach((item) => {
          item.filetype = item.name.split(".").pop().toLowerCase();
        });
        currentPage.setData({
          fileList: list,
        });
      }
    } else if (onDelete) {
      ui.showModal({ title: "确定删除文件?" }, function () {
        list.splice(fileIndex, 1);
        if (loscamOrderId) {
          currentPage.updateFileById(tableType, list, loscamOrderId);
        } else {
          list.forEach((item) => {
            item.filetype = item.name.split(".").pop().toLowerCase();
          });
          currentPage.setData({
            fileList: list,
          });
        }
      });
    }
  },
  updateFileById: function (type, list, id) {
    let currentPage = this;
    updateFile(list, {
      tableType: type,
      tableId: id,
    }).then(async (res) => {
      const data = res.data;
      if (data && data.length > 0) {
        for (let i = 0; i < list.length; i++) {
          const currentIndex = data.findIndex(
            (e) => e.objectId == list[i].objectId
          );
          if (!list[i].fileId) {
            let currentId = data[currentIndex].fileId;
            currentPage.setData({
              ["fileList[" + i + "].fileId"]: currentId,
            });
          }
        }
      }
      await updateFileNum(id, list.length);
      await currentPage.initFileList(type, id);
    });
  },
  // 有两种提交订单的方式所以把更新附件提取为一个方法进行调用
  updateFileList: function (id) {
    let currentPage = this;
    if (currentPage.data.loscamOrderId) {
      currentPage.updateFileById(
        "pallet_issue",
        currentPage.data.fileList,
        currentPage.data.loscamOrderId
      );
    }
    currentPage.initFileList("pallet_issue", id);
    currentPage.backToUpdatePage();
  },

步骤三

更新附件信息数据。

  /**
   * 初始化附件信息
   */
  initFileList: function (type, id) {
    let currentPage = this;
    getFileList(type, id).then((res) => {
      let list = res.data;
      if (list.length > 0) {
        list.forEach((item) => {
          item.filetype &&
            (item.filetype = item.name.split(".").pop().toLowerCase());
        });
      }
      currentPage.setData({
        fileList: list,
      });
    });
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茶茶呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值