微信小程序头像昵称实战篇 open-type="chooseAvatar"

3,353 阅读1分钟

我正在参加「掘金·启航计划」

open-type="chooseAvatar"

2022-08-25

api文档地址: developers.weixin.qq.com/miniprogram…

目前的api变更后,得到的地址为 临时地址, 这个是文档没有说明的, 最佳实践,是需要把得到的地址上传到自己的服务器,然后用服务器返回的地址作为 真实头像的永久地址.

核心点说明:

//获取到api返回的新地址路径
onChooseAvatar(e) {
      this.avatarUrl = e.detail.avatarUrl
      console.log('e.detail', e.detail)
     // this.updateUserInfo();
      this.uploadFile();
    },



/* 上传 头像 转 话格式*/
    uploadFile(){
      uni.uploadFile({
        url: config.webUrl + '/upload/uploadImages',//后台接口
        filePath: this.avatarUrl,// 上传图片 url
        name:'image',
       // formData: this.formData,
        header: {
          'content-type': 'multipart/form-data',
          'token': uni.getStorageSync('token')
        }, // header 值
        success: res => {
          let obj = JSON.parse(res.data)
          console.log('obj', obj)
          if (obj.code == 1) {
           let imgUrl = obj.data.full_path;
           this.userImg = imgUrl;
            this.updateUserInfo();
          } else {
            uni.showToast({
              icon: 'none',
              title: '图片太大,请重新选择!'
            });
          }
        },
        fail: e => {
          this.$toast('上传失败')
        }
      });
    },

这里需要注意, wx.uploadFile 返回的是字符串类型,需要前端自己处理一下数据结构:

完整代码如下:

import config from "@/common/config.js";
import {debounce} from '@/utils/debounce.js'
export default {
  data() {
    return {
      defaultAvatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
      avatarUrl: '',
      nick_name: '',
      userImg: '',
    }
  },

  onLoad() {
    let userInfo = uni.getStorageSync('userInfo') || {};
    let { nick_name,img_url } = {...userInfo};
    this.userImg = img_url;
    this.nick_name = nick_name;
  },
  methods: {
    onChooseAvatar(e) {
      this.avatarUrl = e.detail.avatarUrl
      console.log('e.detail', e.detail)
     // this.updateUserInfo();
      this.uploadFile();
    },



    inputWord: debounce(function(e){
      this.nick_name = e.detail.value
      console.log('this.nick_name.length',this.nick_name.length)
      let str = this.nick_name.trim();
      if(str.length==0){
        this.$toast('请输入合法的昵称')
        return
      }
      if((/[^/a-zA-Z0-9\u4E00-\u9FA5]/g).test(str)){
        this.$toast('请输入中英文和数字')
        return
      }
      this.updateUserInfo()
    }, 1500),


    /* 上传 头像 转 话格式*/
    uploadFile(){
      uni.uploadFile({
        url: config.webUrl + '/upload/uploadImages',//后台接口
        filePath: this.avatarUrl,// 上传图片 url
        name:'image',
       // formData: this.formData,
        header: {
          'content-type': 'multipart/form-data',
          'token': uni.getStorageSync('token')
        }, // header 值
        success: res => {
          let obj = JSON.parse(res.data)
          console.log('obj', obj)
          if (obj.code == 1) {
           let imgUrl = obj.data.full_path;
           this.userImg = imgUrl;
            this.updateUserInfo();
          } else {
            uni.showToast({
              icon: 'none',
              title: '图片太大,请重新选择!'
            });
          }
        },
        fail: e => {
          this.$toast('上传失败')
        }
      });
    },



    updateUserInfo(){
      let self = this;
      uni.showLoading({});
      let params = {
        img_url: this.userImg,
        nick_name: this.nick_name.trim(),
      }
      self.$http.post('updateUserInfo', params).then(res => {
        uni.hideLoading()
        if (res.data.code == 1) {
          self.$toast('修改成功!')
        }else {
          self.$toast(res.data.msg)
        }

      })
    },

  }
}



实际效果图: