![]()
<view class="avatar">
<!-- #ifdef MP-WEIXIN -->
<button class="avatar-content" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
<shop-user-avatar :url="profileData.avatar || ''" width="200" />
<!-- <text class="text">Tap to change avatar</text> -->
</button>
<!-- #endif -->
<!-- #ifndef MP-WEIXIN -->
<button class="avatar-content" @tap="onChooseUserAvatar">
<shop-user-avatar :url="profileData.avatar || ''" width="200" />
<!-- <text class="text">Tap to change avatar</text> -->
</button>
<!-- #endif -->
</view>
// #ifndef MP-WEIXIN
const onChooseUserAvatar = () => {
// 首先检查Android平台的权限
// #ifdef APP-PLUS
try {
// 根据Android版本使用适当的权限
let permissionName: string;
// 获取当前设备信息
const deviceInfo = uni.getSystemInfoSync();
const osVersion = parseInt(deviceInfo.osVersion || '0');
// 对于Android 13+(API 33+),使用新的精细权限
if (deviceInfo.platform === 'android' && osVersion >= 13) {
permissionName = 'android.permission.READ_MEDIA_IMAGES';
} else {
// 对于旧版Android
permissionName = 'android.permission.READ_EXTERNAL_STORAGE';
}
// 检查permission插件是否可用
const globalEvent = uni.requireNativePlugin('globalEvent');
const permission = uni.requireNativePlugin('permission');
if (!permission || typeof permission.requestPermissions !== 'function') {
console.log('权限插件不可用,可能在模拟器中');
// 插件不可用,直接显示照片选择器
showPhotoPicker();
return;
}
// 请求适当的权限
permission.requestPermissions([permissionName], (result: {code: number, data: any}) => {
if (result.code === 0) {
// 权限已授予或已经被授予
showPhotoPicker();
} else {
// 权限被拒绝
uni.showModal({
title: '需要权限',
content: '请允许访问照片权限以选择头像。请在设备设置中授予此权限。',
showCancel: false,
confirmText: '确定'
});
}
});
} catch (error) {
console.log('权限检查过程中出错:', error);
// 出错时直接显示照片选择器
showPhotoPicker();
}
// #endif
// #ifndef APP-PLUS
showPhotoPicker();
// #endif
}
// 新函数,用于显示照片选择器,限制访问权限
const showPhotoPicker = () => {
// 使用现代照片选择器,限制访问权限
uni.chooseImage({
count: 1, // 仅选择一张图片
sourceType: ['album'], // 仅从相册选择,不使用相机
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths
model.imageUrl = tempFilePaths[0]
},
fail: (err) => {
console.log('照片选择被取消或失败', err);
}
})
}
// #endif