微信企業號辦公系統-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

      這些接口都是須要配合着圖片選擇來用的哦微信

相關文章
相關標籤/搜索