Skip to content

头像上传

jsx
const pageData = reactive({
		avatar: proxy.Pub.getImgUrl(proxy.Pub.getStore('userinfo').picImg)
	})
	const formData = reactive({
		picImg: '',
	})

	const chooseAvatar = () => {
		uni.$u.route({
			// 关于此路径,请见下方"注意事项"
			url: 'components/avatar-cropper/avatar-cropper',
			// 内部已设置以下默认参数值,可不传这些参数
			params: {
				// 输出图片宽度,高等于宽,单位px
				destWidth: 300,
				// 裁剪框宽度,高等于宽,单位px
				rectWidth: 300,
				// 输出的图片类型,如果'png'类型发现裁剪的图片太大,改成"jpg"即可
				fileType: 'jpg',
			}
		})
	}
	const uploadImg = async (img) => {
		// #ifdef H5
		proxy.Pub.compressBase64(img, 200, 0.8).then(async img2 => {
			let file = proxy.Pub.dataURLtoFile(img2, new Date().getTime() + '.jpg')
			let res = await proxy.$api.uploadImg(file);
			if (res.status == 1) {
				formData.picImg = res.data;
				changeAvatar();
			}
		})
		// #endif
		// #ifndef H5
		let res = await proxy.$api.uploadImg(img);
		if (res.status == 1) {
			formData.picImg = res.data;
			changeAvatar();
		}
		// #endif

	}
	const changeAvatar = async () => {
		const res = await proxy.$api.editAvatar(formData);
		if (res.status == 1) {
			proxy.Pub.msg(res.msg);
			uni.$emit('update_userinfo');
		}
	}

onLoad(() => {
	uni.$on('uAvatarCropper', path => {
		console.log(path)
		pageData.avatar = path
		// 可以在此上传到服务端
		uploadImg(path);
	})
})
onUnload(() => {
	uni.$off('uAvatarCropper')
})