关于微信小程序上传多张图片的问题

直接帖代码

wxml

<view style="background-color: #ffffff;padding: 30rpx;margin: 25rpx;border-radius: 40rpx;">

  <view style="display: flex;flex-direction: column;margin-left:30rpx">
    <view style="display: flex;margin-top: 40rpx;align-items: center;">
      <view style="margin-right: 70rpx;color: #a8a8a8;word-break: keep-all;">社团名称</view>
      <input bindinput="shetuan_title" placeholder="" maxlength="15" style="border-bottom: 1px solid #a1a1a1;" />
    </view>

    <view style="display: flex;margin-top: 40rpx;align-items: center;">
      <view style="margin-right: 70rpx;color: #a8a8a8;word-break: keep-all; ">社团负责人</view>
      <input bindinput="shetuan_fuzeren" placeholder="" maxlength="10" style="border-bottom: 1px solid #a1a1a1;" />
    </view>

    <view style="display: flex;margin-top: 40rpx;align-items: center;">
      <view style="margin-right: 70rpx;color: #a8a8a8;word-break: keep-all;">负责人联系方式</view>
      <input bindinput="shetuan_lianxi" placeholder="" maxlength="20" style="border-bottom: 1px solid #a1a1a1;" />
    </view>
    <view style="display: flex;margin-top: 40rpx;align-items: center;">
      <view style="margin-right: 70rpx;color: #a8a8a8;word-break: keep-all;">招新群号</view>
      <input bindinput="find_new_number" placeholder="" maxlength="20" style="border-bottom: 1px solid #a1a1a1;" />
    </view>
    <view style="display: flex;margin-top: 40rpx;align-items: center;">
      <view style="margin-right: 70rpx;color: #a8a8a8;word-break: keep-all;">社团描述</view>
      <textarea bindinput="description" auto-height="true" maxlength="100" style="border-bottom: 1px solid #a1a1a1;"></textarea>
    </view>


    <view class="imageRootAll">
      <block wx:for="{{imgList}}" wx:key="index">
        <view class="imgItem">
          <image class="img" src='{{item}}' mode='aspectFill'></image>
          <image class="closeImg" bindtap="DeleteImg" src="/images/close.png" data-index="{{index}}" />
        </view>
      </block>

      <!-- 选择图片按钮 -->
      <view wx:if="{{imgList.length<3}}" class="imgItem" bindtap="ChooseImage">
        <image class="photo" src="../../../images/photo.png"></image>
      </view>
    </view>


  </view>
</view>


<button bindtap="{{chongfu==true?'fabu':''}}" type="primary">发布</button>

前端代码不做过多解释,wx:if控制图片添加的隐藏。

js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    shetuan_title: '',
    shetuan_fuzeren: '',
    shetuan_lianxi: '',
    find_new_number: '',
    description: '',
    fileIDs: [],
    chongfu: true
  },

  shetuan_title(e) {
    var title = e.detail.value
    console.log(title)
    this.setData({
      shetuan_title: title
    })
  },
  shetuan_fuzeren(e) {
    var fuzeren = e.detail.value
    console.log(fuzeren)
    this.setData({
      shetuan_fuzeren: fuzeren
    })
  },
  shetuan_lianxi(e) {
    var lianxi = e.detail.value
    console.log(lianxi)
    this.setData({
      shetuan_lianxi: lianxi
    })
  },
  find_new_number(e) {
    var find_new_number = e.detail.value
    console.log(find_new_number)
    this.setData({
      find_new_number: find_new_number
    })
  },
  description(e) {
    var description = e.detail.value
    console.log(description)
    this.setData({
      description: description
    })
  },
  onLoad(options) {

  },
  //选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 6 - this.data.imgList.length, //默认9,我们这里最多选择6张
      sizeType: ['compressed'], //可以指定是原图还是压缩图,这里用压缩
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log("选择图片成功", res)
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
        console.log("路径", this.data.imgList)
      }
    });
  },
  //删除图片
  DeleteImg(e) {
    wx.showModal({
      title: '要删除这张照片吗?',
      content: '',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  fabu(e) {
    var that = this
    this.setData({
      chongfu: false
    })
    setTimeout(function () {
      that.setData({
        chongfu: true
      })
    }, 1500);
    //let user = app.globalData.userInfo
    let account = wx.getStorageSync('account')
    console.log(account)
    if (!account || !account.name) {
      wx.showToast({
        icon: 'error',
        title: '请先登陆',
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/demo04/demo04',
        })
      }, 1000);
      return
    }

    if (!this.data.shetuan_title || this.data.shetuan_title.length < 4) {
      wx.showToast({
        icon: "error",
        title: '名称不少于4'
      })
      return
    }
    if (!this.data.shetuan_fuzeren || this.data.shetuan_fuzeren.length < 1) {
      wx.showToast({
        icon: "error",
        title: '负责人不为空'
      })
      return
    }
    if (!this.data.shetuan_lianxi || this.data.shetuan_lianxi.length < 1) {
      wx.showToast({
        icon: "error",
        title: '联系方式不为空'
      })
      return
    }
    if (!this.data.find_new_number || this.data.find_new_number.length < 1) {
      wx.showToast({
        icon: "error",
        title: '群号不为空'
      })
      return
    }
    if (!this.data.description || this.data.description.length < 1) {
      wx.showToast({
        icon: "error",
        title: '描述不为空'
      })
      return
    }
    //图片相关
    let imgList = this.data.imgList
    if (!imgList || imgList.length < 1) {
      wx.showToast({
        icon: "error",
        title: '请选择图片'
      })
      return
    }
    // if (!this.data.type || this.data.type == '请选择') {
    //   wx.showToast({
    //     icon: "error",
    //     title: '请选择商品类型'
    //   })
    //   return
    // }
    // if (!this.data.school || this.data.school == '请选择所属学校') {
    //   wx.showToast({
    //     icon: "error",
    //     title: '请选择学校'
    //   })
    //   return
    // }
    // if (!this.data.price || parseInt(this.data.price) < 0 || parseInt(this.data.price) > 999999 || parseInt(this.data.price) / 1 !== parseInt(this.data.price)) {
    //   wx.showToast({
    //     icon: "error",
    //     title: '价格不正确'
    //   })
    //   return
    // }
    // if (!this.data.number || this.data.number < 1 || this.data.number > 999 || parseInt(this.data.number) / 1 !== parseInt(this.data.number) || this.data.number == 0) {
    //   wx.showToast({
    //     icon: "error",
    //     title: '数量不正确'
    //   })
    //   return
    // }
    // if (!wx.getStorageSync('account').lianxi) {
    //   wx.showToast({
    //     icon: "error",
    //     title: '无联系方式'
    //   })
    //   return
    // }


    wx.showLoading({
      title: '申请中...',
    })
    var date = new Date();
    var Y = date.getFullYear();
    var M = date.getMonth() + 1;
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours()
    var min = date.getMinutes()
    if (min < 10) {
      min = '0' + min
    }
    if (M < 10) {
      M = '0' + M
    }
    let shetuan_request_time = Y + "-" + M + "-" + D + " " + H + ":" + min
    const promiseArr = []
    //只能一张张上传 遍历临时的图片数组
    for (let i = 0; i < this.data.imgList.length; i++) {
      let filePath = this.data.imgList[i]
      let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式,获取文件扩展名
      //在每次上传的时候,就往promiseArr里存一个promise,只有当所有的都返回结果时,才可以继续往下执行
      promiseArr.push(new Promise((reslove, reject) => {
        wx.cloud.uploadFile({
          cloudPath: '图片/社团/社团上传图片/' + Y + '/' + M + '/' + D + '/' + new Date().getTime() + suffix,
          filePath: filePath, // 文件路径
        }).then(res => {
          // get resource ID
          console.log("上传结果", res.fileID)
          this.setData({
            fileIDs: this.data.fileIDs.concat(res.fileID)
          })
          reslove()
        }).catch(error => {
          console.log("上传失败", error)
        })
      }))
    }
    //保证所有图片都上传成功
    let db = wx.cloud.database()
    Promise.all(promiseArr).then(res => {
      db.collection('shetuan').add({
        data: {
          shetuan_title: this.data.shetuan_title,
          shetuan_fuzeren: this.data.shetuan_fuzeren,
          shetuan_lianxi: this.data.shetuan_lianxi,
          find_new_number: this.data.find_new_number,
          shetuan_request_time: shetuan_request_time,
          touxiangurl: wx.getStorageSync('account').touxiangurl,
          imageurl: this.data.fileIDs,
          fuzeren_id: wx.getStorageSync('account')._id,
          school: wx.getStorageSync('account').school,
          description: this.data.description,
          member: [],
          shetuan_request:false,
          requset_loadding:true
          //saleid: wx.getStorageSync('account')._id,
          //lianxi: wx.getStorageSync('account').lianxi,
        },
        success: res => {
          wx.hideLoading()
          wx.showToast({
            title: '发布成功',
          })
          //清空数据
          this.setData({
            imgList: [],
            fileIDs: [],
          })
          console.log('发布成功', res)
          wx.navigateBack({
            delta: 1,
          })
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            icon: 'error',
            title: '网络不给力....'
          })
          console.error('发布失败', err)
        }
      })
    })
  },
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

js段的最重要的地方就是异步请求的处理,把所选照片上传云存储后,获取返回值,找到上传图片路径的字段,返回。

在外部用for循环多次上传图片,再返回图片的url,最后放入一个数组。

在上传图片外部写个promise,把以上操作都包括在内,最后在promise.all中放入上传的代码,保证all之前的操作都已经完成,再进行上传操作。

wxss

.imageRootAll {
  margin: 6rpx ;
  display: flex;
  display: -webkit-flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}


.imgItem {
  margin: 6rpx;
  position: relative;
  width: 200rpx;
  height: 200rpx;
  background: gainsboro;
  margin-top: 50rpx;
}
.img {
  width: 100%;
  height: 100%;
}

.closeImg {
  position: absolute;
  right: 0px;
  width: 40rpx;
  height: 40rpx;
}

.photo {
  width: 50%;
  height: 50%;
  margin: 25%;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
在 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` 文件中添加相应的权限配置,以允许选择图片上传文件。 希望这个示例对你有帮助!如果还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值