主要的实现思路就是三步嘛:
- 触发一个点击事件,然后调用uni.chooseImage(Object)函数选择图片
- 在这个函数的回到success中得到选择的图片的文件路径,并接着在这个success回调中调用图片上传的方法uni.uploadFile(Object),然后就得到网络地址.
-
注意:
-
- 这两个回调函数最好是箭头函数,这样this才是指向当前的组件实例的;
-
- 当然也可以在外面先定义一个that,让它等于this,这样你层级再深也可以通过that去拿到this
- 更新视图,将得到的地址赋值给组件实例上的一个属性用于更新视图
以下是代码:
<template>
<view class="flex-bet-c img-height">
<text class="text-size">个人头像</text>
<view class="right-box" @click="changeImg" ref="imgRef">
<u-image v-if="touxiangUrl" :src="touxiangUrl" width="120" height="120" mode="aspectFit" shape="circle" class="mr-10"></u-image>
<u-image v-else src="/static/img/index/touxiang/touxiang.svg" width="120" height="120" mode="aspectFit" shape="circle" class="mr-10"></u-image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
touxiangUrl: '', // http://tmp/AARFFlo0ktwueb94c2f7b3cff9523a5321b0891fae65.jpg
}
},
methods: {
// 自己写的============
// 更换头像
changeImg() {
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], //从相册选择、相机拍摄都可以
success: (res) => {
const tempFile = res.tempFilePaths[0];
// 发起上传的接口
uni.uploadFile({
url: 'http://182.43.79.150:9999/firebackend/file/upload', //仅为示例,非真实的接口地址
filePath: tempFile,
name: 'files',
header: "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjdmODc4MjI4LTQ3OTEtNGRlZC1iNzg3LWQzMGQzNzQwMTEwMiJ9.O8i-EnXuFHJz9G9PxC0Hgo5x_QDhJieFyITsrSprE3qvcCGvwWwScxjaVMOUKK8ppr4SYgcLO19TOrn27VP1Kg",
success: (uploadFileRes) => {
console.log("上传图片:", JSON.parse(uploadFileRes.data));
console.log(this);
let _t=new Date().getTime();
this.touxiangUrl = JSON.parse(uploadFileRes.data).data[0].fileUrl+"?t="+_t;
// // 更新当前页面数据
// // this.updateUserInfo();
// console.log(this.touxiangUrl);
}
})
}
})
},
}
</script>