微信小程序上传图片+图片预览

1.实现效果

在这里插入图片描述

2.实现原理

上传图片:wx.chooseImage()
预览图片:wx.previewImage()
上传文件到服务器 wx.uploadFile()

3.部分代码

data: {
    show:true,//显示选择图片的按钮
    imgList:[],
    maxPhoto:10,//最大上传10张图片
  },
  /**
   * 选择上传方式
   * @param {*} e 
   */
  chooseImg(){
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      success: (res)=> {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            this.chooseWxImage('album')//相册
          } else if (res.tapIndex == 1) {
            this.chooseWxImage('camera')//拍照
          }
        }
      }
    })
  },
  /**
   * 上传照片
   * @param {*} type 
   */
  chooseWxImage: function (type) {
    let {imgList, maxPhoto} = this.data
    if (imgList.length > 10) {
        wx.showToast({
            title: '最多上传10张',
            icon: 'none',
            duration: 2000
        })
        return
    }
    wx.chooseImage({
      count: maxPhoto-imgList.length,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: (res) =>{
        console.log(res)
        let tempFilePaths = res.tempFilePaths //成功后返回的的路径
        console.log(tempFilePaths)
        tempFilePaths.forEach(item=>{
          imgList.push(item)
        })
        this.setData({
          imgList:imgList,
          show: imgList.length >=10? false : true
        })
      }
    })
  },
  /*
    * 图片预览
    * @param e
    */
   previewImg(e){
    let currentUrl = e.currentTarget.dataset.src;
    let urls=this.data.imgList
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: urls// 需要预览的图片http链接列表
    })
  },
  /**
   * 删除上传的图片
   * @param e
   */
  deleteUpload(e) {
    let {index} = e.currentTarget.dataset,{imgList} = this.data
    imgList.splice(index, 1)
    this.setData({
      imgList:imgList,
      show: imgList.length >=10? false : true
    })
  }

4.写在最后🍒

看完本文如果觉得有用,记得点赞+关注+收藏鸭 🍕
更多小程序相关,关注🍥苏苏的bug,🍡苏苏的github,🍪苏苏的码云~
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值