原由:h5中没有微信图像获取,小程序中图方便可以使用微信图像上传
1.在uniapp页面中 info.vue中
<!-- #ifdef H5 -->
<!-- 在h5中执行标签内代码 -->
<button class="avatar-wrapper" open-type="chooseAvatar" @click="upPic">
<image class="avatar" :src="avatar"></image>
</button>
<!-- #endif -->
<!-- #ifdef MP -->
<!-- 在小程序中执行标签内代码 -->
<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
<image class="avatar" :src="avatar"></image>
</button>
<!-- #endif -->
2.在js中使用对应的上传方法
/* 获取微信图像 */
onChooseAvatar(e) {
const {
avatarUrl
} = e.detail
console.log('微信图像', avatarUrl);
uni.uploadFile({
url: '图片上传接口', //仅为示例,非真实的接口地址
filePath: avatarUrl,
name: 'file',
header: {
token: uni.getStorageSync('userInfo').token
},
success: (res) => {
// console.log('上传成功后返回', res);
}
})
},
// uni普通上传
upPic() {
uni.chooseImage({
count: 1, //默认9,这里设置只允许选择一张图片
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //这里选择从相册选择,也可删除此项设置默认拍照和相册两种选择
success: res => {
// 实际开发中,成功的回调函数中是一个上传图片到服务器的接口,这里只是做了简单的效果,实际根据接口需要的参数格式进行上传
// console.log(JSON.stringify(res.tempFilePaths)); 打印的结果是以数组方式返回的,所以我们只需要取第一个值:["blob:http://localhost:8080/c18cded6-ab83-4d0e-9ccd-ce2e402b7d3f"]
let avatarUrl = res.tempFilePaths[0] // 将选择的图片赋值给我们定义的cover
uni.uploadFile({
url: '图片上传接口', //仅为示例,非真实的接口地址
filePath: avatarUrl,
name: 'file',
header: {
token: uni.getStorageSync('userInfo').token
},
success: (res) => {
console.log('上传成功后返回', res);
}
})
}
});
},