fix: 头像转 base64 持久化

WeChat chooseAvatar 返回的 wxfile:// 临时 URL 几天后失效,
头像会变灰。加 util.fileToDataURI 把临时文件读成 data URI
存到本地(限制 512KB,超出走降级方案),从根上解决。
This commit is contained in:
2026-07-08 14:10:25 +08:00
parent ddfcd14252
commit c41b3e138e
2 changed files with 68 additions and 12 deletions
+26 -11
View File
@@ -136,19 +136,34 @@ Page({
// --- Profile handlers ---
onChooseAvatar(e) {
async onChooseAvatar(e) {
const avatarUrl = e.detail.avatarUrl
if (!avatarUrl) return
this.setData({ avatarUrl })
const saved = storage.saveProfile({
nickname: this.data.nickName,
avatarUrl
})
this.setData({
nickName: saved.nickname || this.data.nickName,
avatarUrl: saved.avatarUrl
})
wx.showToast({ title: '头像已更新', icon: 'success', duration: 1200 })
try {
// chooseAvatar returns a wxfile:// temporary URL that expires in a few
// days. Read the bytes and store as a data URI so the avatar survives
// long-term. Falls back to the raw URL on size/read error.
const permanentUrl = await util.fileToDataURI(avatarUrl)
this.setData({ avatarUrl: permanentUrl })
const saved = storage.saveProfile({
nickname: this.data.nickName,
avatarUrl: permanentUrl
})
this.setData({
nickName: saved.nickname || this.data.nickName,
avatarUrl: saved.avatarUrl
})
wx.showToast({ title: '头像已更新', icon: 'success', duration: 1200 })
} catch (err) {
console.warn('avatar convert failed, saving temp URL:', err)
// Fallback: save the raw wxfile URL. Will eventually expire.
this.setData({ avatarUrl })
storage.saveProfile({
nickname: this.data.nickName,
avatarUrl
})
wx.showToast({ title: '头像已更新', icon: 'success', duration: 1200 })
}
},
onNicknameBlur(e) {