小程序上传头像 uni
2021-11-30 本文已影响0人
zhudying
上传头像方式有三种,相册、拍照和默认图片
html
<uni-popup ref="popup" type="bottom" :maskClick="false">
<div class="avatar_container pt40">
<view
class="avatar_container_item"
v-for="item in eventList"
:key="item.name"
@click="chooseItem(item)"
>{{item.name}}</view>
<p class="cancel_text JRound500" @click="close">取消</p>
</div>
</uni-popup>
js
data () {
return {
eventList: [
{
id: 1,
type: 'album',
name: '从相册选择',
},
{
id: 2,
type: 'default',
name: '默认头像',
},
{
id: 3,
type: 'camera',
name: '拍照',
}
]
}
},
// 开启弹窗
open () {
this.$refs.popup.open()
},
// 关闭弹窗
close () {
this.$refs.popup.close()
},
// 点击事件
chooseItem (item) {
if (item.type === 'album') {
this.getLocalAlbum('album') // 相册
}
if (item.type === 'camera') {
this.getLocalAlbum('camera') // 相机
}
if (item.type === 'default') {
// 默认头像
}
this.close()
},
// 获取相册信息、摄像头功能
getLocalAlbum (type) {
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: [type],
success: res => {
const tempFilePaths = res.tempFilePaths;
let avatarPath = tempFilePaths[0];
this.uploadImg(avatarPath)
},
fail: err => {
console.log(err, 'err')
}
})
},
// 图片上传到服务器
uploadImg (avatarPath) {
let token = uni.getStorageSync("token")
wx.uploadFile({
url: config.base_url + '/upload', // 后端api接口
filePath: avatarPath, // chooseImage函数调用后获取的本地文件路劲
name: "file", // 类型
header: {
'Authorization': token
},
success: (res) => {
let data = JSON.parse(res.data) // 返回字符串类型,需要转换
if (data.code === 200) {
}
},
fail: err => {
console.log(err, 'err')
}
});
},