Browse Source

实现头像更换功能:添加onAvatarClick方法,点击头像时弹出更换选择,上传后更新avatarUrl字段

pull/18/head
Default User 1 month ago
parent
commit
8bcbe163e8
  1. 70
      pages/profile/index.js
  2. 3
      pages/profile/index.wxml

70
pages/profile/index.js

@ -1114,4 +1114,74 @@ Page({
}); });
}, },
// 点击头像更换图片
onAvatarClick() {
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFilePaths = res.tempFilePaths;
if (tempFilePaths && tempFilePaths.length > 0) {
this.uploadAvatar(tempFilePaths[0]);
}
},
fail: (err) => {
console.error('选择图片失败:', err);
}
});
},
// 上传头像并更新
async uploadAvatar(filePath) {
wx.showLoading({ title: '上传中...', mask: true });
try {
// 上传图片到服务器
const API = require('../../utils/api.js');
const result = await API.uploadSettlementFile(filePath, 'avatar');
if (result && result.fileUrl) {
const avatarUrl = result.fileUrl;
// 更新本地和全局用户信息
const app = getApp();
const updatedUserInfo = {
...this.data.userInfo,
avatarUrl: avatarUrl
};
// 保存到本地存储和全局状态
app.globalData.userInfo = updatedUserInfo;
wx.setStorageSync('userInfo', updatedUserInfo);
// 更新页面显示
this.setData({ userInfo: updatedUserInfo });
// 上传到服务器更新数据库
const userId = wx.getStorageSync('userId');
if (userId) {
await this.uploadUserInfoToServer(updatedUserInfo, userId, this.data.userType);
}
wx.showToast({
title: '头像更新成功',
icon: 'success',
duration: 2000
});
} else {
throw new Error('上传失败');
}
} catch (error) {
console.error('上传头像失败:', error);
wx.showToast({
title: '上传失败,请重试',
icon: 'none',
duration: 2000
});
} finally {
wx.hideLoading();
}
},
}) })

3
pages/profile/index.wxml

@ -3,7 +3,8 @@
<view style="display: flex; align-items: center;"> <view style="display: flex; align-items: center;">
<image <image
src="{{userInfo.avatarUrl || '/images/你有好蛋.png'}}" src="{{userInfo.avatarUrl || '/images/你有好蛋.png'}}"
style="width: 100rpx; height: 100rpx; border-radius: 50%; margin-right: 20rpx;" style="width: 100rpx; height: 100rpx; border-radius: 50%; margin-right: 20rpx; cursor: pointer;"
bindtap="onAvatarClick"
></image> ></image>
<view> <view>
<view style="font-size: 32rpx; font-weight: bold;">{{userInfo.hiddenPhoneNumber || userInfo.phoneNumber || '未登录'}}</view> <view style="font-size: 32rpx; font-weight: bold;">{{userInfo.hiddenPhoneNumber || userInfo.phoneNumber || '未登录'}}</view>

Loading…
Cancel
Save