微信小程序-文件流图片处理

后端接口正常情况返回文件流图片,异常时返回json

返回示例:

微信小程序-文件流图片处理_第1张图片

微信小程序-文件流图片处理_第2张图片

// 获取图形验证码
  getCaptchaImage(){
    const that = this
    wx.showLoading({ title: '加载中' })

    wx.request({
      url: 'xxxxxx',
      method: "POST",
      data: { a: 123 },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      responseType: 'arraybuffer',
      success: (res)=>{
        if(res && res.data){
          try {
            // 当接口返回的是文件流时,下面的解析会报错
            let unit8Arr = new Uint8Array(res.data)
            let encodedString = String.fromCharCode.apply(null, unit8Arr)
            let decodedString = decodeURIComponent(escape(encodedString))
            let result = JSON.parse(decodedString)
            if(!result.success){
              wx.showToast({
                 title: '操作频繁,请稍后再试',
                 icon: 'none'
              })
            }
          } catch (err) {
            let base64 = wx.arrayBufferToBase64(res.data)
            let captchaImage = "data:image/png;base64," + base64
            that.setData({ captchaImage })
          }
        }else{
          wx.showToast({
             title: '图形验证码获取失败',
             icon: 'none'
          })
        }
      },
      complete: ()=>{
        wx.hideLoading()
      }
    })
  },

参考:https://www.cnblogs.com/letleon/p/14143158.html

你可能感兴趣的:(微信小程序,json)