uniapp上传头像

// 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() // 更新用户信息
		}
	},
    
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值