代码如下:
在xml中的图像那添加绑定事件
<van-image
bindtap="tapImage"
round fit = "cover"
width = "180rpx"
height="180rpx"
src="{{userInfo.avatarUrl}}"
/>
//点击头像 ,更换头像
tapImage(){
if(!this.data.islogin) return; //查看登录没登录
//选择头像图片
wx.chooseMedia({
count: 1,
sourceType: ['album','camera'],
sizeType: ['original','compressed'],
mediaType: ['image'],
success: (res)=>{
console.log(res)
let path = res.tempFiles[0].tempFilePath
//更新头像
let userInfo = this.data.userInfo
userInfo.avatarUrl = path
this.setData({ userInfo : userInfo})
//上传头像到云存储
this.uploadFile(path)
}
})
},
/**
* 上传文件至云存储空间
* @param {String} path 本地临时文件路径
* path: 'wxfile://tmp/xxxxxx/1.jgp'
*/
uploadFile(path){
//生成一个不重复的cloudPath,作为云端文件名
let ext = path.substring(path.lastIndexOf('.'))
let cp = 'img_' + Math.random() + ext
wx.cloud.uploadFile({
filePath: path,
cloudPath:cp,
success:(res)=>{
console.log(res)
}
})
},