zoukankan      html  css  js  c++  java
  • 微信公众号开发图片上传案例

    最近有需求做到公众号开发,有一个上传图片的功能,查看了微信公众号的开发文档,故做如下记录。

    公众号中上传图片的大概流程是:

    1、调用config接口注入权限(接口标识具体参考微信公众平台的附录,我这边需要注入chooseImage、uploadImage)

    wx.config({
          // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
         appId: appId, // 必填,公众号的唯一标识
         timestamp: timestamp, // 必填,生成签名的时间戳
         nonceStr: nonceStr, // 必填,生成签名的随机串
         signature: signature,// 必填,签名,见附录1
         jsApiList: ['chooseImage','uploadImage'] // 必填,需要使用的JS接口列表,所有JS接口列表见微信公众平台附录
    });

    2、调用选择图片(chooseImage)的接口启用选择手机图片的功能,选择完图片后调用上传接口(uploadImage)上传图片到微信的服务器,返回serverId

    var that = this,imageLength=9;
    var image={localIds:[],serverId:[]};  //接收微信接口返回的参数
    var imageUrlList=[]  //用户绑定页面上显示图片的变量
    var mediaIds=[] //接收上传图片返回的serverId(该字段就是调用获取临时素材接口的媒体ID)
    //1.选择图片
    wx.chooseImage({    count: imageLength, //上传图片的张数,最多上传9张 sizeType: ['original', 'compressed'],  // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'],  // 可以指定来源是相册还是相机,默认二者都有 success: function(res) { that.images.localIds = res.localIds; //展示图片 for (var i=0;i<res.localIds.length;i++) { that.imageUrlList.push(res.localIds[i]); } var uploadCount = 0; var localIdLength = that.images.localIds.length; var upload = function() {
                  // 2.上传图片 wx.uploadImage({ localId:that.images.localIds[uploadCount],  //选择的图片标识 success: function(res) { that.images.serverId.push(res.serverId);  //微信返回的该图片的服务ID,可调用获取素材的接口下载到自己项目的应用服务器 var mediaIdsLength = that.mediaIds.length; var flag = false; if (mediaIdsLength>0) { for (var i=0;i<mediaIdsLength;i++) { if (that.mediaIds[i].id == value.id) { that.mediaIds[i].mediaId.push(res.serverId); } flag = true; } } if (!flag) { var item = {id:'',mediaId:[]}; item.id = value.id;item.mediaId.push(res.serverId); that.mediaIds.push(item); } //如果还有照片,继续上传 uploadCount++; if (uploadCount < localIdLength) { upload(); } }, fail: function(res) { alert(JSON.stringify(res)); } }); };
              //循环上传 upload(); }, fail: function(res) { alert(JSON.stringify(res)); } });

     3、最后调用获取临时素材的接口,

    http请求方式: GET,https调用
    https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
    请求示例(示例为通过curl命令获取多媒体文件)
    curl -I -G "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"

    access_token:接口调用凭证
    media_id:媒体ID,(上传图片返回的serverId)

    接口返回:
    {
    "video_url":DOWN_URL
    }
  • 相关阅读:
    tp5.1 多级控制器
    JS中三个点(...)是什么鬼?
    vue reqwest与fetch的使用
    new Vue({ render: h => h(App), }).$mount('#app')到底什么意思
    ant design vue 表格和国际化的使用
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
  • 原文地址:https://www.cnblogs.com/mark8080/p/8707485.html
Copyright © 2011-2022 走看看