微信上传图片通识v1.0

正常流程

正常流程一般是要经常wx.config,然后使用wx.chooseImage就可以选择图片,然后传递给我们相应的图片信息,基于这个图片信息,我们可以用作图片的预览以及传到对应的业务服务器(或者微信的服务器)。

image.png

备注:

1 微信的图片不会长期存储,即使会也不建议存储到微信方,建议业务部分存储一份。

2 建议图片相关的服务,做成公共服务,然后每个业务需要的时候,增加业务标识即可

相关代码

以下以前端签名为例。

获取服务端ticket

  @action initWeixinSDK = (appId) => {
    fetch(API.GET_WEIXIN_JSAPI_TICKET + '?appId=' + appId, {
      method: 'post'
    }).then(res => {
      if (res.success) {
        // 请求次数受限,全局缓存jsapi_ticket
        localStorage.setItem('jsapi_ticket', res.data.ticket); 
        localStorage.setItem('created_at', new Date().getTime() / 1000);
        this.initWXConfig();
      }
    });
  }
复制代码

wx.config

  initWXConfig = () => {
    const nonceStr = this.randomString(16);
    const url = window.location.href.split("#")[0];
    const timestamp = String(parseInt((new Date().getTime() / 1000)));
    const string1 = 'jsapi_ticket=' + localStorage.getItem('jsapi_ticket') + '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' +url ;
    const signature = sha1(string1);
    wx.config({
      debug: false,
      appId: localStorage.getItem('wxAppId'),
      timestamp: timestamp,
      nonceStr: nonceStr,
      signature: signature,
      // 可以从服务端获取, 但如果变动不大 建议写死到工具侧,提升性能减少链路
      jsApiList: [
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'onMenuShareTimeline',
        'onMenuShareAppMessage'
      ]
    });
    wx.error(function(res) {
      sessionStorage.setItem('wxError', JSON.stringify(res));
      //记录错误
      log({
        time: moment().format('YYYY-MM-DD HH:mm:ss'),
        type: 'weixinError',
        app: 'clinicPlatformPatientApps',
        content: JSON.stringify({
          errorMsg: JSON.stringify(res),
          version: 'P3.3.3',
          platfrom: navigator.userAgent
        })
      })
    })
  }
复制代码

其中随机字符串方法:

//随机字符生成算法
  randomString = (len = 32) => {
    const $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let str = '';
    for (var i = 0; i < len; i++) {
      str += $chars.charAt(Math.floor(Math.random() * $chars.length));
    }
    return str;
  }
复制代码

选择图片

  @action uploadImageAct = (total, resolve, reject) => {
    if (total > 9) {
      total = 9;
    }
    const that = this;
    wx.chooseImage({
      count: total,
      sizeType: ['original'],
      success: function (res) {
        that.chosenLocalIds = res.localIds;
        that.uploadIndex = 0;
        that.localDataList = [];
        that.mediaIdList = [];
        Toast.loading('图片上传中...', 90000);
        that.uploadWeixinImg(resolve, reject);
      },
      fail: function (err) {
        Modal.alert('警告', '请确保微信打开相册权限');
        reject('chooseImage error');
      }
    });
  }
复制代码

上传图片

// 上传图片到微信服务器
  @action uploadWeixinImg = (resolve, reject) => {
    const that = this;
    const localId = (this.chosenLocalIds[this.uploadIndex]).toString();
    this.getLocalImageData(localId);
    wx.uploadImage({
      localId: localId,
      isShowProgressTips: 0,
      success: function (res) {
        that.uploadIndex++;
        that.mediaIdList.push(res.serverId);
        localStorage.setItem('serverId', res.serverId);
        if (that.uploadIndex < that.chosenLocalIds.length) {
          that.uploadWeixinImg(resolve, reject);
        } else {
          Toast.hide();
          Toast.success('上传成功', 2);
          // 兼容处理,某版本之后,不允许使用localId访问预览图片
          const localIdList = window.__wxjs_is_wkwebview ? that.localDataList : that.chosenLocalIds;
          resolve({ mediaIdList: that.mediaIdList.slice(), localIdList: localIdList.slice() });
        }
      },
      fail: function (data) {
        sessionStorage.setItem('上传失败返回数据', JSON.stringify(data))
        Toast.offline('上传失败,请重试', 2);
        reject('uploadImage error');
      }
    })
  }
复制代码

其中兼容方法:获取本地图片

  @action getLocalImageData = localId => {
    const that = this;
    wx.getLocalImgData({
      localId: localId, // 图片的localID
      success: function (res) {
        that.localDataList.push(res.localData);
      }
    });
  }
复制代码

相关文档

更多文章

image.png

猜你喜欢

转载自juejin.im/post/7080334543525249037
今日推荐