uniapp 微信小程序获取头像,上传服务器

html 头像UI

<button class="user-avatar flex-center" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
  <image
    class="img"
    :src="showAvatat()"
     mode="scaleToFill"
  />
</button>

方法

// 点击头像弹出选择框
const onChooseAvatar = (e: any) => {
  const { detail } = e
  uni.compressImage({
    src: detail.avatarUrl,
    quality: 80,
    success: res => {
      uploadFile(res.tempFilePath);
    }
  })
}


/* 上传头像 */
const uploadFile = (fileUrl: string) => {
  console.log(fileUrl, 'fileUrl')
  uni.uploadFile({
    url: `/home/changeAvatar` ,
    filePath: fileUrl,
    name: 'file',
    header: {
      Authorization: userInfo?.token || '',
    },
    success: (res: any) => {
      const data = JSON.parse(res.data)
      if(data.code === 200) {
        useUserInfo.updateUserInfo({
          avatar: data.result || 'http://qn.hongqidl.com/hq-artist/head/mine/default-avator.png'
        })
        uni.$u.toast('修改头像成功')
      }
    },
    fail: e => {
      uni.showToast({
        title: '上传失败',
        duration: 2000,
        icon: "none"
      });
    }
  });
}

posted @ 2024-09-03 11:32  DL·Coder  阅读(704)  评论(0)    收藏  举报