微信企业号办公系统-JSSDK上传图片(多图上传)

在开发微信企业号办公系统中,涉及到了图片上传功能,一开始使用的flash插件上传方法,在苹果手机上能够调用相机直接拍摄照片,但在安卓手机上只能选择照片。html

微信jssdk-api带有一套完整的调用选择本地图片上传的功能,不少朋友在问到多图上传的问题。在这里分享一下本身的作法,其实并非本身的作法,就是彻底按照微信开发文档的作法,不少朋友可能没有仔细看文档,或者文档内容太多因此不想看,而后就不知道作法了,我这里挂出来,是这样作的android

var images = {
    localId: [],
    serverId: []
  };

  

 document.querySelector('#chooseImage').onclick = function () {
    wx.chooseImage({
      success: function (res) {
        images.localId = res.localIds;
        alert('已选择 ' + res.localIds.length + ' 张图片');
      }
    });
  };

  // 5.2 图片预览
  document.querySelector('#previewImage').onclick = function () {
    wx.previewImage({
      current: 'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
      urls: [
        'http://img3.douban.com/view/photo/photo/public/p2152117150.jpg',
        'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
        'http://img3.douban.com/view/photo/photo/public/p2152134700.jpg'
      ]
    });
  };

  // 5.3 上传图片
  document.querySelector('#uploadImage').onclick = function () {
    if (images.localId.length == 0) {
      alert('请先使用 chooseImage 接口选择图片');
      return;
    }
    var i = 0, length = images.localId.length;
    images.serverId = [];
    function upload() {
      wx.uploadImage({
        localId: images.localId[i],
        success: function (res) {
          i++;
          //alert('已上传:' + i + '/' + length);
          images.serverId.push(res.serverId);
          if (i < length) {
            upload();
          }
        },
        fail: function (res) {
          alert(JSON.stringify(res));
        }
      });
    }
    upload();    /*********************多张图片,这里上传使用的是递归******************************/
  };

  // 5.4 下载图片
  document.querySelector('#downloadImage').onclick = function () {
    if (images.serverId.length === 0) {
      alert('请先使用 uploadImage 上传图片');
      return;
    }
    var i = 0, length = images.serverId.length;
    images.localId = [];
    function download() {
      wx.downloadImage({
        serverId: images.serverId[i],
        success: function (res) {
          i++;
          alert('已下载:' + i + '/' + length);
          images.localId.push(res.localId);
          if (i < length) {
            download();
          }
        }
      });
    }
    download();      /*********************多张图片,这里下载使用的是递归******************************/

  };

  多图上传或者下载都是使用的递归方法,在android或者IOS中都是行得通的(在这里多说一句,有些接口,Android行得通,IOS却不行;IOS能够的,Android可能又会有问题,固然这只是极个别现象,用多了就会发现)。api

      这些接口都是须要配合着图片选择来用的哦微信

相关文章
相关标签/搜索