小程序-修改用户头像

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>
相关推荐
Forget the Dream28 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek31 分钟前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学
Forget the Dream1 小时前
设计模式之代理模式
java·c++·设计模式·代理模式
帅的飞起来1 小时前
设计模式--spring中用到的设计模式
java·spring·设计模式
萧寂1732 小时前
微信小程序自定义轮播图指示点样式
微信小程序·小程序
張葒兵3 小时前
记一次命令行启动springboot项目的问题 java -jar的问题
java·spring boot·jar
zr想努力3 小时前
Lua的table类型的增删改查操作
java·开发语言·lua
人类群星闪耀时4 小时前
Apache Flink:实时数据流处理的终极武器
struts·flink·apache