小程序-修改用户头像

1、调用拍照 / 选择图片

// 修改头像

const onAvatarChange = () => {

// 调用拍照 / 选择图片

uni.chooseMedia({

// 文件个数

count: 1,

// 文件类型

mediaType: ['image'],

success: (res) => {

console.log(res)

// 本地临时文件路径 (本地路径)

const { tempFilePath } = res.tempFiles[0]

},

})

}

2、获取图片路径

3、上传文件

// 文件上传

uni.uploadFile({

url: '/member/profile/avatar',

name: 'file',

filePath: tempFilePath,

success: (res) => {

if (res.statusCode === 200) {

const avatar = JSON.parse(res.data).result.avatar

profile.value.avatar = avatar

}

},

})

4、更新头像

5、完整代码实现

javascript 复制代码
<template>
<!-- 头像 -->
  <view class="avatar">
     <view class="avatar-content" @tap="onAvatarChange">
       <image class="image" :src="profile?.avatar" mode="aspectFill" />
       <text class="text">点击修改头像</text>
     </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getMemberProfileAPI } from '@/services/profile'
import type { ProfileDetail } from '@/types/member'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 获取个人信息
const profile = ref<ProfileDetail>()
const getMemberProfileData = async () => {
  const res = await getMemberProfileAPI()
  console.log('获取个人信息', res)
  profile.value = res.result
}
// 页面加载
onLoad(() => {
  getMemberProfileData()
})

// 修改头像
const onAvatarChange = () => {
  // 调用拍照 / 选择图片
  uni.chooseMedia({
    // 文件个数
    count: 1,
    // 文件类型
    mediaType: ['image'],
    success: (res) => {
      console.log(res)
      // 本地临时文件路径 (本地路径)
      const { tempFilePath } = res.tempFiles[0]
      // 文件上传
      uni.uploadFile({
        url: '/member/profile/avatar',
        name: 'file',
        filePath: tempFilePath,
        success: (res) => {
          if (res.statusCode === 200) {
            const avatar = JSON.parse(res.data).result.avatar
            profile.value.avatar = avatar
          }
        },
      })
    },
  })
}
</script>
相关推荐
racerun30 分钟前
小程序导航设置更多内容的实现方法
小程序
说私域33 分钟前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
FrankYoou34 分钟前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
mg66839 分钟前
微信小程序入门实例_____快速搭建一个快递查询小程序
微信小程序·小程序
麦兜*1 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了1 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
天河归来1 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
weixin_478689762 小时前
十大排序算法汇总
java·算法·排序算法
码荼2 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud