小程序-修改用户头像

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>
相关推荐
摇滚侠2 小时前
Spring Boot 3零基础教程,创建第一个 Spring Boot 3 应用,Spring Boot 3 外部配置,笔记03
java·spring boot·笔记
没有bug.的程序员4 小时前
服务网格 Service Mesh:微服务通信的终极进化
java·分布式·微服务·云原生·service_mesh
2501_915921435 小时前
iOS 是开源的吗?苹果系统的封闭与开放边界全解析(含开发与开心上架(Appuploader)实战)
android·ios·小程序·uni-app·开源·iphone·webview
西京刀客6 小时前
开源 ETL(Extract,Transform,Load)工具之Apache Hop
开源·apache·etl·hop
南尘NCA86667 小时前
企业微信防封防投诉拦截系统:从痛点解决到技术实现
java·网络·企业微信
怪兽20148 小时前
SQL优化手段有哪些
java·数据库·面试
ss2738 小时前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
Deschen9 小时前
设计模式-原型模式
java·设计模式·原型模式
麦麦鸡腿堡9 小时前
Java的动态绑定机制(重要)
java·开发语言·算法