微信小程序上传头像和昵称持久化保存

简介: 微信小程序上传头像和昵称持久化保存

微信小程序上传头像和昵称持久化保存

1. 持久化步骤

因为通过微信头像昵称填写功能获取到头像是一个临时头像,这个url只能一段时间内在微信访问,并且无法在公网访问这个url。所以非常有必要把这个url转成我么实际可用的头像到数据库中。让头像持久化的在微信和公网任何位置都能访问。


这里我们使用url转base64字符串的方式,持久化图片成base64字符串。如果是自己上传图片还需要考虑图片大小和压缩图片的问题,这里我们直接采用微信的头像上传接口,直接帮我们快捷压缩和裁剪图片,灰常的好用。话不多说,来看代码


2. 页面效果


d6daef1d5d5f4fb9b3867c769f3f1200.png

5e3099c7b3334d9bbadb1c9040380128.png


a6fbef0273034c0197363a5e6c12bd15.png

3. 代码实现

1. uniapp小程序

安装image-tools

npm i image-tools --save

2. 原生小程序

新建一个util工具类js。加上一个function

/**
 * 图片url链接转base64
 * @param {String} url 图片链接
 * @returns 转base64后的值或者报错信息
 */
const imgUrlToBase64 = (url) => {
  return new Promise((resolve, reject) => {
    if (!url) {
      reject('请传入url内容');
    }
    if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(url)) {
      // 图片地址
      const image = new Image();
      // 设置跨域问题
      image.setAttribute('crossOrigin', 'anonymous');
      // 图片地址
      image.src = url;
      image.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = image.width;
        canvas.height = image.height;
        ctx.drawImage(image, 0, 0, image.width, image.height);
        // 获取图片后缀
        const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
        // 转base64
        const dataUrl = canvas.toDataURL(`image/${ext}`);
        resolve(dataUrl || '');
      }
    } else {
      // 非图片地址
      reject('非(png/jpe?g/gif/svg等)图片地址');
    }
  });
};

2. 页面使用

1. 完善用户信息(昵称头像)弹窗

 <u-modal v-model="showAuthorizeUser" :show-title="false"
               :show-confirm-button="false">
        <view class="slot-content">
          <div class="auth-card">
            <div class="img">
              <img class="avatar-img"
                   :src="userInfoTemp.avatarurl"
                   v-if="userInfoTemp.avatarurl&& userInfoTemp.avatarurl!=''"
                   mode="widthFix">
              <img class="avatar-img"
                   v-else
                   src="/static/logo-min.png"
                   mode="widthFix">
            </div>
            <div class="title">{{bname}}</div>
            <div class="content">邀请您补全个人信息<br></br>(昵称、头像)</div>
            <div style="margin-left: 100rpx;margin-right: 100rpx">
              <u-form ref="uForm">
                <u-form-item label="头像">
                  <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" slot="right">
                    <image class="avatar"
                           :src="userInfoTemp.avatarurl"
                           v-if="userInfoTemp.avatarurl&& userInfoTemp.avatarurl!=''"></image>
                    <image class="avatar"
                           v-else
                           src="/static/logo-min.png"></image>
                  </button>
                </u-form-item>
                <u-form-item label="昵称">
                  <input type="nickname" class="weui-input" @blur="userNameInput" placeholder="请输入昵称"/>
                </u-form-item>
              </u-form>
            </div>
          </div>
          <div class="auth-btncard">
            <div class="btn-unok"><u-button :hair-line='false' :custom-style="customStyleUnOk" @click="showAuthorizeUser=false"> 拒绝</u-button></div>
            <div class="btn-ok"><u-button :hair-line='false' :custom-style="customStyleOk" @click="authUser"> 允许</u-button></div>
          </div>
        </view>
   </u-modal>

2. js部分

<script>
        import { pathToBase64, base64ToPath } from 'image-tools'
        //如果是原生小程序这里就import我们写的那个function。图片url转base64的
        export default {
            data() {
                return {
                    userInfoTemp:{
                        id:'',
                        name:'',
                        avatarurl:''
                    },
                customStyleUnOk: {
                    marginTop: '20rpx', // 注意驼峰命名,并且值必须用引号包括,因为这是对象
                    border:'none',
                    color:'gray'
                },
                customStyleOk: {
                    marginTop: '20rpx', // 注意驼峰命名,并且值必须用引号包括,因为这是对象
                    border:'none',
                    color:'#157DFB'
                },
                // 用户基本信息
                userInfo: null,
                // 是否弹出登录注册授权弹窗
                showAuthorizeUser: false,
        }
    },
    methods: {
      openUserSet(){
        this.userInfoTemp.id = this.userInfo.id;
        this.userInfoTemp.name = this.userInfo.name;
        this.userInfoTemp.avatarurl = this.userInfo.avatarurl;
        console.log(this.userInfoTemp)
        this.showAuthorizeUser = true;
      },
      authUser(){
        if(this.userInfoTemp.name && this.userInfoTemp.name!=''){
          if(this.userInfoTemp.avatarurl && this.userInfoTemp.avatarurl!=''){
            this.showAuthorizeUser = false;
            this.$api.saveUserInfo(this.userInfoTemp, res => {
              this.userInfo.name = this.userInfoTemp.name;
              this.userInfo.avatarurl = this.userInfoTemp.avatarurl;
              uni.setStorageSync('userInfo',this.userInfo)
              this.$interactive.toast('保存成功!')
              this.showAuthorizeUser = false;
            })
          }else{
            this.$interactive.toast('头像不能为空!')
          }
        }else{
          this.$interactive.toast('昵称不能为空!')
        }
      },
      //获取昵称输入内容
      userNameInput(e){
        this.userInfoTemp.name = e.detail.value
      },
      onChooseAvatar(e) {
        pathToBase64( e.detail.avatarUrl).then(path => {
          this.userInfoTemp.avatarurl = path
        }).catch(error => {
          console.log(error)
        })
      }
    }
}
</script>

3. css部分

.auth-card{
    text-align: center;
    .avatar-img{
        width: 150rpx;
        height: 150rpx;
        overflow: hidden;
        border-radius: 100%;
        margin-top: 30rpx;
    }
    .title{
        font-size: 20rpx;
    }
    .content{
        margin-top: 10rpx;
    }
}
.avatar-wrapper{
    width: 150rpx;
    height: 100rpx;
    color: #333 !important;
    text-align: center !important;
    border: none !important;
    border-radius:0 !important;
    background-color:transparent !important;
}
.avatar-wrapper::after {
  border: none !important;
}
.auth-btncard{
    .btn-unok{
        width: 50%;
        float: left;
    }
    .btn-ok{
        width: 50%;
        float: left;
        margin: 0;
        padding: 0;
        border: 0px solid transparent;  //自定义边框
        outline: none;    //消除默认点击蓝色边框效果
        u-button{
            margin: 0;
            padding: 0;
            border: 0px solid transparent;  //自定义边框
            outline: none;    //消除默认点击蓝色边框效果
        }
    }
}


目录
相关文章
|
2月前
|
小程序 JavaScript
小程序授权获取昵称
小程序授权获取昵称
|
9月前
|
存储 缓存 小程序
微信小程序如何获取微信昵称和头像
微信小程序如何获取微信昵称和头像
173 0
|
3月前
|
存储 小程序 API
uniapp项目实战第五章:小程序Pinia持久化
uniapp项目实战第五章:小程序Pinia持久化
102 0
|
8月前
|
小程序
微信小程序获取头像和名称
微信小程序获取头像和名称
67 0
|
4月前
|
小程序 API
微信小程序获取昵称,头像
微信小程序获取昵称,头像
|
4月前
|
缓存 小程序 API
小程序实现登录持久化
小程序实现登录持久化
139 0
|
5月前
|
存储 缓存 小程序
小程序如何实现登录数据持久化
小程序如何实现登录数据持久化
88 0
|
5月前
|
小程序 JavaScript 程序员
小程序新方法 open-type获取头像昵称
小程序新方法 open-type获取头像昵称
127 0
|
9月前
|
小程序 JavaScript
微信小程序获取用户头像和姓名
微信小程序获取用户头像和姓名
149 0
|
9月前
|
小程序 API
微信小程序获取昵称,头像
微信小程序获取昵称,头像
136 0