小程序-修改用户头像

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>
相关推荐
长河5 小时前
Java开发者LLM实战——LangChain4j最新版教学知识库实战
java·开发语言
Cyan_RA96 小时前
SpringMVC @RequestMapping的使用演示和细节 详解
java·开发语言·后端·spring·mvc·ssm·springmvc
喵手8 小时前
玩转Java网络编程:基于Socket的服务器和客户端开发!
java·服务器·网络
再见晴天*_*9 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
hdsoft_huge12 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
破无差12 小时前
《赛事报名系统小程序》
小程序·html·uniapp
雨白13 小时前
Java 多线程指南:从基础用法到线程安全
android·java
Hungry_Shark13 小时前
IDEA版本控制管理之使用Gitee
java·gitee·intellij-idea
赛姐在努力.13 小时前
《IDEA 突然“三无”?三秒找回消失的绿色启动键、主菜单和项目树!》
java·intellij-idea
猎板PCB黄浩13 小时前
从废料到碳减排:猎板 PCB 埋容埋阻的绿色制造革命,如何实现环保与性能双赢
java·服务器·制造