微信小程序上传照片,限制格式,限制大小,公用方法

本文详细介绍了在微信小程序中实现图片上传功能的方法,包括如何选择图片、预览、压缩及上传图片到服务器的全过程。文章重点讲解了利用微信小程序API进行图片操作的具体步骤,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法
/**
 * 选择上传照片
 * page_that:调用方法的页面,
 * cb_key:返回参数数组的名称
 * count:上传张数
 * 返回值:数组
 */
function selecImg(page_that, cb_key, count) {
  console.log("选择图片");
  wx.chooseImage({
    count: count,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function(res) {
      console.log(res)
      var pathArray = [];
      var PicNums = res.tempFiles.length;
      for (var inta = 0; inta < PicNums; inta++) {
        var size = res.tempFiles[inta].size;
        var path = res.tempFiles[inta].path;
        var formatImage = path.split(".")[(path.split(".")).length - 1];
        console.log("图片格式" + formatImage)
        if (formatImage != "png" && formatImage != "jpg" && formatImage != "jpeg") {
          return wx.showToast({
            title: '只能上传.png、.jpg、.jpep 格式',
            icon: 'none',
            image: '',
            duration: 2000,
            mask: true,
          })
        }
        if (config.image_size < size) {
          return wx.showToast({
            title: '图片大小限制:' + (config.image_size / 1024 / 1024) + "MB",  ///config.image_size 配置文件中设置
            icon: 'none',
            image: '',
            duration: 1500,
            mask: true,
          })
        }
        pathArray.push(path);
        if (inta == PicNums-1) {
          var cb = {};
          cb[cb_key] = pathArray;
          page_that.setData(cb);
        }
      }
    }
  })
}
.wxml
<image src="../../Image/bg_pic1.png" mode='widthFix' style="width:100px" bindtap='Oncarm' data-whopic='idcard'></image>
.js 调用

  Oncarm: function(e) {
    var whopic = e.currentTarget.dataset.whopic;
    /**
     * page_that:调用方法的页面,
     * cb_key:返回参数数组的名称,
     * count:上传张数,
     * 返回值:数组
     */
    util.selecImg(this, whopic, 1);
  },

在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值