// HTML 代码
<view class="headimage" @tap="onChooseImg">
<image :src="userInfo.work_image" mode=""></image>
</view>
// js代码
methods: {
// 更换头像
async onChooseImg() {
const chooseImageRes = await this.chooseImage(1); // 打开相机/相册 得到的file文件
const uploadImageRes = await this.uploadImage(chooseImageRes[0]); // 上传file文件转换为线上地址
this.uploadInfo('avatar', uploadImageRes.fullurl) // 修改用户信息接口
this.userInfo.avatar = uploadImageRes.fullurl; // 更新头像
},
// 选择照片
async chooseImage(count = 1) {
return new Promise((resolve, reject) => {
uni.chooseImage({
count: count, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: res => {
resolve(res.tempFilePaths);
}
});
}).catch(e => {
console.log(e);
});
},
// 上传文件
async uploadImage(url) {
const that = this;
return new Promise((resolve, reject) => {
that.$u.toast('上传中...');
uni.uploadFile({
url: that.$API_URL + '/api/common/upload',
filePath: url,
name: 'file',
success: res => {
res = JSON.parse(res.data);
if (res.code === 1) {
that.$u.toast('上传成功');
resolve(res.data);
} else {
that.$u.toast('上传失败');
}
},
complete: e => {
uni.hideLoading();
}
});
}).catch(e => {
console.log(e);
});
},
async uploadInfo(key,value) {
const data = {}
data[key] = value
const res = await uploadInfo(data)
if(res.code == 1) {
this.$tool.toast('修改成功')
this.getUserInfo() // 更新用户信息
}
},
}