微信小程序获取头像昵称 保存头像到服务器

微信官方推荐的替代做法:

头像昵称填写 | 微信开放文档 (qq.com)

 wxml

<button class="avatar" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
  <image src="{
   
   {avatarUrl}}"></image>
</button> 
<input type="nickname" class="weui-input" placeholder="请输入昵称"/>

js

// pages/my/my.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        avatarUrl: defaultAvatarUrl,
    },
    onChooseAvatar(e) {
        const {
            avatarUrl
        } = e.detail
        this.setData({
            avatarUrl,
        })
        //  将头像上传到服务器
        wx.uploadFile({
            filePath: avatarUrl,
            header: {'content-type': 'multipart/form-data'},
            name: 'avatarImg',
            url: 'xxxxxxx', //服务器端接收图片的路径
            success: function (res) {
                console.log(res); //发送成功回调
            },
            fail: function (res) {
                console.log(res); //发送失败回调,可以在这里了解失败原因
            }
        })
    },
    onLoad: function (n) {

    },
    onShow: function () {
        wx.login({
            success(res) {
                if (res.code) {
                    //发起网络请求
                    console.log('登录' + res.code)
                } else {
                    console.log('登录失败!' + res.errMsg)
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

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

    },

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

    },

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

    },

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

    },

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

    },
})

wxss

.avatar{
    width: 80px;
    height: 80px;
    padding:0;
    background: none;
}
.avatar image{
    width: 80px;
    height: 80px;
    border-radius: 100px;
}
.weui-input{
    width: 90%;
    height: 60px;
    margin:20px auto;
    background: #eee;
    border-radius: 5px;
    padding-left: 15px;
}

猜你喜欢

转载自blog.csdn.net/Ghjkku/article/details/129252117
今日推荐