一、绑定点击上传图片事件
1.image标签双向绑定图片地址;
2.设置“修改头像”点击按钮;
<view class="userIcon">
<image :src="imageSrc" mode=""></image>
<view class="userIconBtn" @click="selectFile"> 修改头像 </view>
</view>
二、用户选择图片并且限制图片大小
selectFile() {
let vm = this;
wx.chooseImage({
sizeType: ['original'], //可选择原图或压缩后的图片
sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
success: res => {
//图片小于或者等于1M时 可以执行获取图片
if (res.tempFiles[0].size <= 1000000) {
vm.imageSrc = res.tempFilePaths[0];
//页面渲染图片
this.userIcon();
//图片传到后台
} else {
uni.showToast({
title: '上传图片不能大于1M!',
icon: 'none',
duration: 2000
})
}
}
})
},
wx.chooseImage(Object object) | 微信开放文档
三、将图片上传到后端
wx.uploadFile({
filePath: this.imageSrc,
name: 'avatarfile',
url: 'http://地址',
header: {
Authorization: 'Bearer ' + uni.getStorageSync('accessToken'),
"Content-Type": "multipart/form-data",
'Content-Type': 'application/json;charset=UTF-8'
},
success: (res) => {
uni.showToast({
title: "头像更改成功",
icon: 'none',
duration: 2000
})
},
fail: () => {
console.log("失败...");
}
})