The normal process

The normal process is usually to wx.config, and then use wx.chooseImage to select the picture, and then pass the corresponding picture information to us, based on this picture information, we can use the picture preview and upload to the corresponding business server (or wechat server).

Remark:

1 Wechat pictures will not be stored for a long time, and even if they are, it is not recommended to store them in wechat. It is suggested to store a copy in the business section.

2 suggest picture-related services to be made public, and then add business identifiers for each business when needed

The relevant code

The following is an example of the front-end signature.

Obtain the server ticket

  @action initWeixinSDK = (appId) = > {
    fetch(API.GET_WEIXIN_JSAPI_TICKET + '? appId=' + appId, {
      method: 'post'
    }).then(res= > {
      if (res.success) {
        // The number of requests is limited. The global cache is jsapi_ticket
        localStorage.setItem('jsapi_ticket', res.data.ticket); 
        localStorage.setItem('created_at'.new Date().getTime() / 1000);
        this.initWXConfig(); }}); }Copy the code

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,
      // It can be obtained from the server, but if the change is not significant, it is recommended to write to the tool side to improve performance and reduce links
      jsApiList: [
        'chooseImage'.'previewImage'.'uploadImage'.'downloadImage'.'onMenuShareTimeline'.'onMenuShareAppMessage']}); wx.error(function(res) {
      sessionStorage.setItem('wxError'.JSON.stringify(res));
      // Record error
      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
        })
      })
    })
  }
Copy the code

Where random string method:

// Random character generation algorithm
  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;
  }
Copy the code

Choose picture

  @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('Picture uploaded... '.90000);
        that.uploadWeixinImg(resolve, reject);
      },
      fail: function (err) {
        Modal.alert('warning'.'Please make sure wechat has the permission to open the album');
        reject('chooseImage error'); }}); }Copy the code

To upload pictures

// Upload image to wechat server
  @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('Upload successful'.2);
          // Compatible processing, after a version, do not allow the use of localId to access the preview image
          const localIdList = window.__wxjs_is_wkwebview ? that.localDataList : that.chosenLocalIds;
          resolve({ mediaIdList: that.mediaIdList.slice(), localIdList: localIdList.slice() }); }},fail: function (data) {
        sessionStorage.setItem('Upload failed to return data'.JSON.stringify(data))
        Toast.offline('Upload failed, please try again'.2);
        reject('uploadImage error'); }})}Copy the code

Compatible methods: Obtain local images

  @action getLocalImageData = localId= > {
    const that = this;
    wx.getLocalImgData({
      localId: localId, // localID of the image
      success: function (res) { that.localDataList.push(res.localData); }}); }Copy the code

The related documents

  • JSSDK description link

More articles

  • More of my wechat related articles