微信小程序用户头像持久化存储

730 阅读1分钟

我们在获取微信用户头像的时候微信官方给我门返回的地址都是有时效的,但是我们需求是长久存储和展现的,那么怎么实现呢?

下面给大家提供一套完整的解决方案和思路:

第一步:使用微信官方的方法获取用户头像:

注意:open-type="chooseAvatar" 表明是获取头像的;

onChooseAvatar是我获取头像的方法。

<button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
  <image class="avatar" src="{{avatarUrl}}"></image>
</button> 

第二步:在onChooseAvatar方法里面进行两步操作----下载和上传服务器

	const handleChooseavatar = async (e) => {
		avatar.value = e.avatarUrl
             //上传自己对应的文件服务器
			await wx.uploadFile({
			url: 你的文件服务器地址,
			filePath: avatar.value,
			name: 'file',
			formData: {
				path: '',
			},
			header: {
				'Blade-Auth': `bearer 根据接口判断是否需要token`
			},
			success: async (res2) => {
                        //拿到服务器永久地址
			},
			fail: (res) => {
				console.log('上传图片失败', res);
			}
		})
		
	}

这样你的用户头像就是永久的了 不再是微信提供的临时头像 。