优化头像上传功能

This commit is contained in:
yzy committed 2026-01-20 19:37:12 +08:00
1 parent 9392fe9938
commit 4187454008
1 file changed
+78 -1
+78 -1
View File
@@ -102,6 +102,83 @@
} }
} }
// 选择并上传头像
const chooseAndUploadAvatar = async () => {
uni.chooseImage({
count: 1, // 最多选择一张图片
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
sourceType: ['album', 'camera'], // 从相册选择或拍照
success: async (res) => {
const tempFilePaths = res.tempFilePaths;
if (tempFilePaths.length > 0) {
const filePath = tempFilePaths[0];
// 显示上传中提示
uni.showLoading({
title: 'Uploading...'
});
try {
const uploadRes = await new Promise((resolve, reject) => {
uni.uploadFile({
url: 'https://takway-ai.top/test/app-api/member/user/upload-avatar',
filePath: filePath,
name: 'avatarFile',
header: {
'Authorization': `Bearer ${userStore.token}`
},
success: (uploadResult) => {
try {
const data = JSON.parse(uploadResult.data);
resolve(data);
} catch (e) {
console.error('Failed to parse upload response:', uploadResult.data);
reject(new Error(`Failed to parse response: ${uploadResult.data}`));
}
},
fail: (error) => {
console.error('Upload failed:', error);
reject(error);
}
});
});
if (uploadRes && uploadRes.code === 0) { // 假设成功状态码为0
// 更新用户数据中的头像URL
userData.value.avatar = uploadRes.data;
userStore.updateUserInfo('avatar', uploadRes.data);
uni.showToast({
title: 'Upload success',
icon: 'success'
});
} else {
uni.showToast({
title: uploadRes?.message || 'Upload failed',
icon: 'none'
});
}
} catch (error) {
console.error('Upload error:', error);
uni.showToast({
title: error?.message || 'Upload failed',
icon: 'none'
});
} finally {
uni.hideLoading();
}
}
},
fail: (error) => {
console.error('Choose image error:', error);
uni.showToast({
title: 'Failed to select image',
icon: 'none'
});
}
});
}
/** /**
* @desc 跳转至登录页面 * @desc 跳转至登录页面
*/ */
@@ -183,7 +260,7 @@
<view <view
class="w-16 h-16 rounded-full border-2 border-theme border-solid mr-4 p-3 bg-[#ddd] overflow-hidden"> class="w-16 h-16 rounded-full border-2 border-theme border-solid mr-4 p-3 bg-[#ddd] overflow-hidden">
<!-- 直接使用原生 image 标签 --> <!-- 直接使用原生 image 标签 -->
<image src="/static/image/head.png" class="w-full h-full object-cover" @click="test()" /> <image :src="userData?.avatar || '/static/image/head.png'" class="w-full h-full object-cover" @click="chooseAndUploadAvatar" />
</view> </view>
<view class="flex flex-col justify-center items-start gap-1"> <view class="flex flex-col justify-center items-start gap-1">