小程序多图上传后单张替换功能实现

上篇文章解决了多图上传的预览和删除功能,然后按照学习要求需要做一个替换图片的功能,发现网上基本查不到这个字眼,因为替换不就是把图片删除再上传一张嘛,但其中其实有一些微小的区别,替换是把指定位置的图片替换,而删除后再添加就是在最后新增图片,顺序不一样。处理思路其实很简单,在触发点击时间事件的回调信息里可以取到当前选择的图片的index,根据这个index去做操作,新增的图片就不能像多张上传那样把图片URL直接push进数组,应该直接赋值,Array[index]=图片url就行了。

下图为替换第二张图片的效果
image.png
image.png

wxml和js文件

 <!--替换的WXML-->
        <image src="../../img/replaceImg.png" class="replaceImg" mode="aspectFill" bindtap="replaceImg"
        data-index='{{idx}}' data-item='{{item}}'/>
 /***替换图片 */
  replaceImg: function (e) {
    console.log("替换返回的e", e)
    const index = e.currentTarget.dataset.index; //index是图片的索引,从0开始
    const {
      upload,
      chooseImgs
    } = this.data;

    console.log("替换前的上传upload数组", upload)
    console.log("替换前的本地chooseImgs数组", chooseImgs)

    this.uploadImgOne(index)//在index位置上传单张图片
  },

把index值传入单张图片上传的函数里

 /***单图上传 */
  async uploadImgOne(index) {
    const that = this;
    const {
      upload,
      chooseImgs
    } = this.data;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: async function (res) {
        console.log(res)
        const newChooseImgs = res.tempFilePaths; //拿到图片本地URL(URL,长度)
        const imgInfo = res.tempFiles; //拿到图片的信息(URL,大小,长度)
        // 判断选择的图片是否符合要求
        for (let i = 0; i < imgInfo.length; i++) {
          console.log("尺寸", imgInfo[i].size);
          // 判断图片尺寸,大于10M不行
          if (imgInfo[i].size / 1024 / 1024 >= 10) {
            wx.showModal({
              title: '提示', // 标题
              content: "图片超过10MB啦~", // 内容
              showCancel: false, // 是否显示取消按钮
              confirmText: '确定', // 确认按钮的文字
            });
            return
          }
          // 判断图片格式
          const imgSplit = imgInfo[i].path.split(".");
          const imgSLen = imgSplit.length;
          console.log("格式", imgSplit, imgSLen, imgSLen - 1);
          //分割图片URL后有四段,但是下标是0,1,2,3,所以需要总数减1才是后缀的下标
          if (["jpg", "jpeg", "png"].includes(imgSplit[imgSLen - 1])) {
            console.log("格式正确");
          } else {
            console.log("格式错误");
            utils.showModalInfo({
              content: "请选择正确的图片格式上传",
            });
            return
          }
        }
        console.log("选择图片时", res, chooseImgs, newChooseImgs);
        //此时chooseImgs的池子里是空,需要把选择到newChooseImgs里的图片传入本地chooseImgs池子里
        // newChooseImgs.forEach(item => {
        //   chooseImgs.push(item);
        // });
        chooseImgs[index] = newChooseImgs;
        console.log("选择图片后", chooseImgs, newChooseImgs); //此时池子里有图片
        console.log("显示添加图片", chooseImgs.length);
        if (chooseImgs.length > 0) {
          //图如果满了1张,不显示加图
          if (chooseImgs.length >= 9) {
            that.setData({
              //隐藏加号
              hideAdd: true
            })
          } else {
            that.setData({
              hideAdd: false
            })
          }
          // 显示预览图
          that.setData({
            chooseImgs
          });

          //  网络请求 上传图片await
          // for (let item of newChooseImgs) {
          console.log("单张图片", newChooseImgs)
          console.log("本地数组", chooseImgs)
          console.log("图片下标", index)

          let resImage = await uploadFile(newChooseImgs[0])
          console.log("替换后上传返回的内容resImage:", resImage)

          const upload = that.data.upload; //把每次选择的图放到数组的选择替换位置
          const resStatus = resImage.data.status
          const resName = resImage.data.name
          console.log("后缀", resName)
          if (resStatus == 1) {
            const imgURL = {
              imgURL: 'xxxxx' + resName
            }
            upload[index] = imgURL;

            that.setData({
              "upload": upload,
              //"chooseImgs": chooseImgs
            })
            console.log("替换后的上传数组", upload)
          } else {
            that.getToken()
            let resImage = await uploadFile(newChooseImgs[0])
            console.log("替换后上传返回的内容resImage:", resImage)

            const upload = that.data.upload; //把每次选择的图放到数组的选择替换位置
            const resName = resImage.data.name
            const imgURL = {
              imgURL: 'xxxxxxx' + resName
            }
            upload[index] = imgURL;
            that.setData({
              "upload": upload,
              //"chooseImgs": chooseImgs
            })
            console.log("替换后的上传数组", upload)
          }
        }
      }
    })
  },

总体和多图上传差不多,控制只能选择一张图片,然后主要就是下面两行变化,直接赋值不用Push
chooseImgs[index] = newChooseImgs;
upload[index] = imgURL

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容