微信小程序上传多张图片

微信小程序可以上传单张,多张,数量不超过一定数量

以4张为例子

wxml

   <view class="add-img-box">
      <view class="add-img">
        <view bindtap="addImg" class="addimg-btn">+</view>
        <view class="img-box">
          <view class="img-con" wx:for="{{addImgUrl}}" wx:key="index">
            <image class="imgArr" bindtap="previewImg" bindlongpress="deleteImage" data-url="{{item}}" src="{{item}}" role="img" />
            <view class="imgDel">
              <text class="iconfont icon-shanchu" bindtap="imgSingleDel" data-index="{{index}}"></text>
            </view>
          </view>
        </view>
      </view>
      <view class="limit-tip">最多上传4张</view>
    </view>

wxss

.add-img-box {
  width: 750rpx;
  padding-top: 1rpx;
  background: #FFFFFF;
  margin-top: 20rpx;
  /* border: 1px solid hotpink; */
  padding: 0 30rpx;
}

.add-img {
  width: 650rpx;
  height: 160rpx;
  padding-bottom: 1rpx;
  background: #FAFAFA;
  /* margin: 0 30rpx 0 !important; */
  display: flex;
  align-items: flex-start;
  /* border: 1px solid yellow; */
}

.add-img .addimg-btn {
  font-size: 50rpx;
  width: 110rpx;
  height: 140rpx;
  vertical-align: middle;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10rpx 0 0rpx 15rpx;
  background-color: #fff;
  box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(231, 231, 231, 0.5);
  border-radius: 6rpx;
  /* border: 1px solid wheat; */
}

.add-img .img-box {
  width: 550rpx;
  padding-top: 20rpx;
  overflow-x: scroll;
  height: 150rpx;
  border-radius: 6rpx;
  display: flex;
  align-items: flex-start;
}

.img-box .imgArr {
  position: relative;
  width: 110rpx;
  height: 120rpx;
  margin-left: 25rpx;
  box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(231, 231, 231, 0.5);
}

.add-img>image {
  width: 110rpx;
  height: 120rpx;
  margin-left: 25rpx;
  box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(231, 231, 231, 0.5);
}

.imgArr image {
  width: 100%;
  height: 100%;
}

/* 删除 */
.imgDel {
  position: absolute;
  right: -18rpx;
  top: -20rpx;
  width: 40rpx;
  height: 40rpx;
}

.imgDel .iconfont {
  font-size: 40rpx;
  color: #E02020;
}

.img-con {
  position: relative;
  /* width: 526rpx; */
  height: 110rpx;
  border-radius: 6rpx;
  display: flex;
  align-items: flex-start;
}

js

  /*页面的初始数据*/
  data: {
    imageUrl: app.globalData.URL,
    addImgUrl: [],
    imgs: [],
    all_file_path: [],
    file_id: [],
    current_file_path: [],
    current_file_id: []

  },
  addImg() {
   wx.chooseMedia({
      count: 4,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      success: async function (res) {
        var tempFilePaths = res.tempFiles.map(file => file.tempFilePath);
        var existingPaths = that.data.addImgUrl;

        // 截取前 4 张图片
        var newPaths = tempFilePaths.slice(0, 4 - existingPaths.length);
        var remainingPaths = tempFilePaths.slice(newPaths.length);

        if (remainingPaths.length > 0 && remainingPaths.length < newPaths.length) {
          // 剩余图片数量不足以上传时,不上传新的图片
          wx.showToast({
            title: '最多上传四张',
            icon: 'error',
          });
          return;
        }

        if (existingPaths.length + newPaths.length > 4) {
          // 添加的图片超过了限制
          wx.showToast({
            title: '最多上传四张',
            icon: 'error',
          });
          return;
        }

        for (var i = 0; i < newPaths.length; i++) {
          var path = newPaths[i];
          if (existingPaths.indexOf(path) !== -1) {
            wx.showToast({
              title: '该照片已经存在',
              icon: 'none'
            });
            continue;
          }
          if (that.data.addImgUrl.length > 3) {
            wx.showToast({
              title: '最多上传四张',
              icon: 'error',
            })
            return
          }
          existingPaths.push(path);

          try {
            var result = await that.uploadFile(path);
            var data = JSON.parse(result.data);
            console.log('data data',data);
            var file_path = app.globalData.URL + data.detail.path + data.detail.name;
            var file_id = data.detail.id;
            that.setData({
              current_file_path: [...that.data.current_file_path, file_path],
              current_file_id: [...that.data.current_file_id, file_id]
            });
          } catch (err) {
            console.error('上传失败', err);
          }
        }

        if (remainingPaths.length > 0) {
          // 存在剩余图片,继续调用选择图片 API
          wx.chooseMedia({
            count: remainingPaths.length,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            sizeType: ['compressed'],
            success: async function (res) {
              var tempFilePaths = res.tempFiles.map(file => file.tempFilePath);

              // 递归调用 addImg1 函数,继续上传剩余图片
              that.addImg(tempFilePaths);
            }
          });
        } else {
          // 所有图片上传完成,更新数据
          var allFilePaths = [...that.data.all_file_path];
          var allFileIds = [...that.data.file_id];

          for (var i = 0; i < that.data.current_file_id.length; i++) {
            if (allFileIds.indexOf(that.data.current_file_id[i]) === -1) {
              allFileIds.push(that.data.current_file_id[i]);
              allFilePaths.push(that.data.current_file_path[i])
            }
          }

          that.setData({
            addImgUrl: existingPaths,
            imgs: existingPaths,
            all_file_path: allFilePaths,
            file_id: allFileIds
          });
          console.log('file_id1 final', that.data.file_id,that.data.all_file_path);
        }
      }
    });
},
    

  uploadFile(path) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: app.globalData.URL + 'api/common/upload',
        filePath: path,
        name: 'file',
        success: function (res) {
          resolve(res);
        },
        fail: function (err) {
          reject(err);
        }
      });
    });
  },

    // 点击已选图片进行删除
  imgSingleDel(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var current_file_path = that.data.current_file_path;
    var current_file_id = that.data.current_file_id;
    var all_file_path = that.data.all_file_path;
    var file_id = that.data.file_id;
    var addImgUrl = this.data.addImgUrl;

    wx.showModal({
      title: '提示',
      content: '确定要删除该图片吗?',
      success(res) {
        if (res.confirm) {
          // 从 current_file_path1 和 current_file_id1 中删除对应的文件信息
          current_file_path.splice(index, 1);
          current_file_id.splice(index, 1);
          all_file_path.splice(index, 1);
          file_id.splice(index, 1);
          addImgUrl.splice(index, 1);

          that.setData({
            current_file_path,
            current_file_id,
            all_file_path,
            file_id,
            addImgUrl
          });

          console.log('file_id', file_id);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 图片预览
  previewImg(e) {
    let url = e.currentTarget.dataset.url;
    console.log('url', url);
    wx.previewImage({
      current: url,
      urls: this.data.imgs
    })
  },

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 Uniapp 中实现微信小程序多张图片上传,可以按照以下步骤进行操作: 1. 在页面中创建一个按钮,用于触发选择图片的操作。 2. 在按钮的点击事件中,调用 `uni.chooseImage` 方法来选择图片。这个方法会返回选择的图片的临时文件路径。 3. 将选择的图片路径保存在一个数组中。 4. 在页面中展示已选择的图片,可以使用 `v-for` 指令来遍历已选择的图片数组,使用 `uni.previewImage` 方法来预览图片。 5. 创建一个提交按钮,在点击事件中调用 `uni.uploadFile` 方法,将选择的图片上传到服务器。 下面是一个示例代码: ```html <template> <view> <button @tap="chooseImage">选择图片</button> <view v-for="(image, index) in imageList" :key="index"> <image :src="image" mode="aspectFit" @tap="previewImage(index)" /> </view> <button @tap="uploadImages">上传图片</button> </view> </template> <script> export default { data() { return { imageList: [], // 存放已选择的图片路径 }; }, methods: { chooseImage() { uni.chooseImage({ count: 9, // 最多可以选择的图片张数 success: (res) => { // 将选择的图片路径保存到 imageList 数组中 this.imageList = res.tempFilePaths; }, }); }, previewImage(index) { uni.previewImage({ urls: this.imageList, // 需要预览的图片路径列表 current: this.imageList[index], // 当前显示的图片链接 }); }, uploadImages() { // 遍历已选择的图片路径,逐个上传 this.imageList.forEach((image) => { uni.uploadFile({ url: 'https://your-upload-api-url', // 上传图片的接口地址 filePath: image, name: 'file', // 上传文件对应的 key 值 formData: {}, // 其他额外的参数 success: (res) => { console.log(res.data); }, }); }); }, }, }; </script> ``` 请注意替换示例代码中的上传接口地址为你自己的接口地址。另外,需要在 `manifest.json` 文件中添加相应的权限配置,以允许选择图片上传文件。 希望这个示例对你有帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值