uniApp更新头像的大致过程
页面结构,绑定onAvtarChange事件
<!-- 头像 -->
<view class="avatar" @click="onAvtarChange">
<view class="avatar-content">
<image class="image" :src="profile?.avatar" mode="aspectFill" />
<text class="text">点击修改头像</text>
</view>
</view>
function onAvtarChange() {
uni.chooseMedia({
// 选择文件的数量
count: 1,
// 文件类型 只能选择图片文件
type: 'image',
success: (res) => {
// tempFilePath 临时文件路径
const { tempFilePath } = res.tempFiles[0]
uni.uploadFile({
url: '/member/profile/avatar', //接口地址
name: 'file', //接口参数名
filePath: tempFilePath, //临时文件路径
success: (success) => {
console.log(success)
if (success.statusCode === 200) {
const { avatar } = JSON.parse(res.data).result
// 当前页面更新头像
profile.value!.avatar = avatar
// 更新 Store 头像
memberStore.profile!.avatar = avatar
uni.showToast({
title: '上传成功',
icon: 'success',
})
} else {
uni.showToast({
title: '上传失败,请更换头像重试',
icon: 'none',
duration: 2000,
})
}
},
})
},
})
}
}
},
})
},
})
}