小程序-修改用户头像

1、调用拍照 / 选择图片

// 修改头像

const onAvatarChange = () => {

// 调用拍照 / 选择图片

uni.chooseMedia({

// 文件个数

count: 1,

// 文件类型

mediaType: 'image',

success: (res) => {

console.log(res)

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

const { tempFilePath } = res.tempFiles0

},

})

}

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>
相关推荐
古法安卓4 小时前
Android-日志系统源码解析
android·java·android studio
小夏coding5 小时前
从"一把梭"到"精妙拆解" —— 滑动窗口计时框架的设计演进
java·后端
MacroZheng6 小时前
同事问我:"Claude Code经常失忆,不怕它把项目搞炸?",我:"怕,三个Markdown文件给它装个永不丢失的外置大脑!"
java·人工智能·后端
十年Java程序媛7 小时前
深度实战:JDK21 虚拟线程 + HikariCP 生产正确配比、坑点、监控全套
java·spring boot
xiaoqiMikko7 小时前
有人在搜一个不存在的 Tomcat 版本
java·tomcat
用户31268748772011 小时前
ConcurrentHashMap 怎么保证线程安全?从分段锁到 CAS+synchronized
java
vipxieliang11 小时前
ValidX vs Apache Commons Validator:功能与性能对比
java·spring boot
SimonKing11 小时前
升级Spring Boot 4后,从 Jackson 2 到 3,到底有哪些变化
java·后端·程序员
吃饱了得干活11 小时前
一篇讲清楚Spring Boot:自动装配、启动器、过滤器、拦截器、设计模式
java·spring boot·后端
lhldsg13 小时前
AI零售系统实战指南:从架构设计到落地部署全解析
java·人工智能·小程序·uni-app·零售