August 22, 2023 [The WeChat applet obtains the temporary path of the avatar and converts it to base64 encoding and sends it to the background for storage]

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.


Preface

提示:这里可以添加本文要记录的大概内容:

Reference link

WeChat applet uploads avatar and nickname and saves them persistently

The latest version of the WeChat applet to obtain the user's avatar, nickname and mobile phone number

Mini program image conversion to base64 solution (multiple solutions)


Fill in the avatar nickname | WeChat open document

提示:以下是本篇文章正文内容,下面案例可供参考

1. Obtain the avatar code

wxml code

<!-- 获取头像和名字 -->
<view style="margin: 20rpx 0;display: flex;flex-direction: column;align-items: center;">
  <button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
     <image class="avatar" src="{
     
     {avatarUrl}}" style="width: 100rpx;height: 100rpx;" mode="aspectFit"></image>
  </button>
  <input type="nickname" class="weui-input" placeholder="请输入昵称" />
</view>

js

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
    
    
  data: {
    
    
    avatarUrl: defaultAvatarUrl,
  },
  // 获取路径
  onChooseAvatar(e) {
    
    
    const {
    
     avatarUrl } = e.detail 
    this.setData({
    
    
      avatarUrl,
    })
  }
})

Insert image description here

2. Usage steps

1. Click on the avatar

Insert image description here

Click on the WeChat avatar. The printed link is a temporary link and will fail when copied to an external browser.
Whether you click on the WeChat avatar, upload a picture, or take a photo, you will get a path.

http://tmp/DXGZXiE0qJ0Teb5748474b9a6cf28e2dd60c91f22c42.jpeg
The external browser cannot be opened, but the WeChat developer tool can open the preview

2. Convert the image to base64 format and send it to the backend

The code is as follows (example):

// 图片转64代码
base64(url, type) {
    
    
  return new Promise((resolve, reject) => {
    
    
    wx.getFileSystemManager().readFile({
    
    
      filePath: url, //选择图片返回的相对路径
      encoding: 'base64', //编码格式
      success: res => {
    
    
        // resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
        resolve(res.data)
      },
      fail: res => reject(res.errMsg)
    })
  })
},

In the resolve return value in success, some need to add data:image/png, and some do not. It depends
on whether there is any problem with your background acquisition. I do not need the base64 prefix for background acquisition here. I kept the annotation

Insert image description here

I have already written the method of obtaining the avatar path before, and use it together with the base64 conversion method.

Insert image description here

// 获取头像
  onChooseAvatar(e) {
    
    
    const {
    
    
      avatarUrl
    } = e.detail
    this.setData({
    
    
      avatarUrl,
    })
    console.log(avatarUrl, "avatarUrl");
    // 执行图片转base64方法
    this.base64(avatarUrl, "png").then(res => {
    
    
      console.log(res, 'base64路径') //res是base64路径
      this.setData({
    
    
        'form.base64': res
      })
    })
    console.log(avatarUrl, '1');
  },
  // 图片转64
  base64(url, type) {
    
    
    return new Promise((resolve, reject) => {
    
    
      wx.getFileSystemManager().readFile({
    
    
        filePath: url, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => {
    
    
          // resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
          resolve(res.data)
        },
        fail: res => reject(res.errMsg)
      })
    })
  },

form.base64 is


Summarize

All code
wxml

<!--pages/mine/user-edit/user-edit.wxml-->
<!-- 用户授权头像昵称页面 -->
<view class="userInfo-container">
  <view style="background-color: #F7F7F7;height: 20rpx;"></view>
  <van-cell-group>
    <van-cell title-width="400rpx">
      <view slot="title" class="cell-title">
        头像<text style="color: #999;font-size: 22rpx;">(点击上传头像或更换头像)</text>
      </view>
      <view class="cell-value">
        <button class="cell-btn" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
          <image src="{
     
     {avatarUrl}}" mode="aspectFill"></image>
        </button>
      </view>
    </van-cell>

    <van-cell title-width="400rpx">
      <view slot="title">
        昵称<text style="color: #999;font-size: 22rpx;">(点击使用微信昵称或填写昵称)</text>
      </view>
      <input type="nickname" value="{
     
     {form.nickName}}" class="weui-input" bindinput="onChangeInput" placeholder="请输入昵称" />
    </van-cell>
    <van-cell title="手机号">
      <input wx:if="{
     
     {form.phone}}" type="nickname" value="{
     
     {form.phone}}" class="weui-input" bindinput="onChangeInput" disabled />
      <button wx:else="" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" size="mini">一键获取</button>
    </van-cell>
  </van-cell-group>
  
  <view style="color: #C8C9CC; font-size: 24rpx;padding: 10rpx 30rpx;">
    为杜绝垃圾信息,手机号绑定后不可更改。敬请谅解!
  </view>
  <!-- <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号码</button> -->
  <view class="form-btn">
    <van-button type="primary" round block color="#F24129" bindtap="onSave">确定</van-button>
  </view>


  <!-- <input type="nickname" class="weui-input" placeholder="请输入昵称" /> -->
  <image src="{
     
     {img}}" mode="aspectFill"></image>

</view>

style

/* pages/mine/user-edit/user-edit.wxss */

.userInfo-container{
    
    
  /* margin: 20rpx 0; */
  background-color: #f7f7f7;
  height: 100vh;
}

.cell-title{
    
    
  line-height: 100rpx;
}
.cell-value{
    
    
  display: flex;
  justify-content: flex-end;
}

.cell-btn {
    
    
  padding: 0;
   width: 100rpx;
  height: 100rpx;
  margin: 0;
}
.cell-btn image{
    
    
  width: 100rpx;
  height: 100rpx;
}

/* 提交按钮 */
.form-btn{
    
    
  margin: 20rpx;

}

js code

// pages/mine/user-edit/user-edit.js

var app = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
    
    
  /**
   * 页面的初始数据
   */
  data: {
    
    
    // 头像
    avatarUrl: defaultAvatarUrl, // 头像链接
    form: {
    
    
      nickName: "", // 用户昵称
      base64: "", // 图片
      phone: "", // 手机号
    },
    img: "",
  },

  // 获取头像
  onChooseAvatar(e) {
    
    
    const {
    
    
      avatarUrl
    } = e.detail
    this.setData({
    
    
      avatarUrl,
    })
    console.log(avatarUrl, "avatarUrl");
    // 执行图片转base64方法
    this.base64(avatarUrl, "png").then(res => {
    
    
      console.log(res, 'base64路径') //res是base64路径
      this.setData({
    
    
        'form.base64': res
      })
    })
    console.log(avatarUrl, '1');
  },
  // 图片转64
  base64(url, type) {
    
    
    return new Promise((resolve, reject) => {
    
    
      wx.getFileSystemManager().readFile({
    
    
        filePath: url, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => {
    
    
          // resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
          resolve(res.data)
        },
        fail: res => reject(res.errMsg)
      })
    })
  },
  // 输入昵称
  onChangeInput(e) {
    
    
    // console.log(e.detail.value, '昵称');
    this.setData({
    
    
      "form.nickName": e.detail.value
    })
  },
  // 点击确定
  onSave() {
    
    
    console.log(this.data.form);
    // 说明手机号不存在,必须先授权手机号
    if (!this.data.form.phone) {
    
    
      wx.showToast({
    
    
        title: '请先授权手机号',
        icon: 'none',
        duration: 1500
      })
      return
    }
    let data = {
    
    
      yh_img: this.data.form.base64,
      yh_name: this.data.form.nickName,
      user_id: wx.getStorageSync('openid')
    }
    app.http.request("/purchase/usereid", data, "POST").then(res => {
    
    
      console.log(res, '提交头像和名字');
      if (res.code == 100) {
    
    
        // this.setData({
    
    
        //   img: res.data.yh_img
        // })
        wx.showToast({
    
    
          title: '修改成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(() => {
    
    
          let pages = getCurrentPages(); //页面栈
          let beforePage = pages[pages.length - 2];
          var obj = JSON.parse(JSON.stringify(beforePage)).options
          let query = ""
          let aUrl = []
          let fnAdd = function (key, value) {
    
    
            return key + '=' + value
          }
          for (var k in obj) {
    
    
            aUrl.push(fnAdd(k, obj[k]))
          }
          query = aUrl.join('&')
          wx.switchTab({
    
    
            url: '/' + beforePage.route + "?" + query
          })
          wx.reLaunch({
    
    
            url: '/' + beforePage.route + "?" + query
          })
        }, 1500)
      }
    })

  },

  // 允许授权手机号
  getPhoneNumber(e) {
    
    
    console.log(e, '执行方法');
    console.log(e.detail.errMsg, '返回信息'); //
    console.log(e.detail.iv, '加密算法的初始向量'); //加密算法的初始向量
    console.log(e.detail.encryptedData, '包括敏感数据在内的完整用户信息的加密数据'); //包括敏感数据在内的完整用户信息的加密数据
    if (e.detail.encryptedData && e.detail.iv) {
    
    
      wx.checkSession({
    
     //监测登录是否过期
        success: () => {
    
    
          let data = {
    
    
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            session_key: wx.getStorageSync('sessionKey'),
            user_id: wx.getStorageSync('openid'),
          }
          app.http.request("/Phone/phoneadd", data, "POST").then(res => {
    
    
            console.log(res, '添加手机号到后台');
            this.getUserPhone()
          })
        },
        fail: () => {
    
     // session_key 已经失效,需要重新执行登录流程

        }
      })
    }
  },
  // 获取自己电话
  getUserPhone() {
    
    
    app.http.request("/Phone/phonelist", {
    
    
      user_id: wx.getStorageSync('openid'),
    }, "POST").then(res => {
    
    
      console.log(res.data, '自己的电话');
      wx.setStorageSync('userphone', res.data)
      this.setData({
    
    
        "form.phone": res.data
      })
    })

  },
  // 获取用户原有信息
  getUserInfo() {
    
    
    app.http.request("/Userlist/userlist", {
    
    
      user_id: wx.getStorageSync('openid'),
    }, "POST").then(res => {
    
    
      console.log(res, '用户信息');
      if (res.code == 100) {
    
    
        this.setData({
    
    
          avatarUrl: res.data.yh_img,
          'form.nickName': res.data.yh_name,
          'form.phone': res.data.yh_phone
        })
        if(this.data.form.nickName=="微信用户"){
    
    
          this.setData({
    
    
            'form.nickName': "",
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
    
    // 如果没有用户id
    if (!wx.getStorageSync('openid')) {
    
    
      wx.navigateTo({
    
    
        url: '/pages/login/index'
      })
    } else {
    
    
      this.getUserInfo()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
    

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
    

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    
    

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    
    

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    
    

  }
})

Insert image description here

Guess you like

Origin blog.csdn.net/qq_51055690/article/details/129283789