123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- <template>
- <view class="updata-img">
- <view class="updata-title-box">
- <view class="updata-title-title font-title ">{{ data.title }} <span style="color: #f56c6c;"
- v-if="data.required">*</span> </view>
- <view class="updata-title-text font-text ">{{ data.text }}</view>
- </view>
- <view class="updata-img-box" @click="updataFile">
- <image :src="img" style="width: 117px;height: 75px;" />
- </view>
- </view>
- </template>
- <script setup>
- import { ref, toRaw } from 'vue';
- import { uploadFile } from '../../api/file';
- import { getToken } from '@/utils/auth'
- import config from '@/config'
- const baseUrl = config.baseUrl
- const props = defineProps({
- data: {
- type: Object,
- default: {
- title: '上传头像',
- text: '上传您的头像',
- img: "/static/img/updata-user-img.png"
- },
- },
- });
- const emit = defineEmits(['onSubmit']);
- const file = ref(null);
- const img = ref(props.data.img);
- function updataFile() {
- wx.chooseMessageFile({
- count: 1,
- type: 'file',
- success: (res) => {
- {
- const tempFilePath = res.tempFiles[0].path; // 获取临时文件路径
- const fs = wx.getFileSystemManager(); // 获取文件系统管理器
- wx.uploadFile({
- url: baseUrl + '/common/upload', // 服务器接口地址
- filePath: tempFilePath, // 本地文件路径(通过 wx.chooseImage 获取)
- name: 'file', // 文件对应的 key(服务器接收字段名)
- formData: { // 额外表单数据
- file: res.tempFiles[0],
- },
- header: {
- 'Authorization': 'Bearer ' + getToken(), // 自定义请求头
- },
- success(res) {
- const data = JSON.parse(res.data);
- file.value = data.url;
- emit('onSubmit', { key: props.data.key, url: data.url })
- fs.readFile({
- filePath: tempFilePath,
- encoding: 'base64', // 指定编码格式
- success: (fileRes) => {
- const base64Data = 'data:image/png;base64,' + fileRes.data; // 拼接 Base64 前缀
- img.value = base64Data;
- uni.showToast({
- title: '上传成功',
- icon: 'none'
- })
- },
- fail: (err) => {
- uni.showToast({
- title: '上传失败',
- icon: 'none'
- })
- console.error(' 转换失败:', err);
- }
- });
- },
- fail(error) {
- console.log(' 上传失败', error);
- uni.showToast({
- title: '上传失败',
- icon: 'none'
- })
- }
- });
- }
- }
- });
- }
- function getFile() {
- return toRaw(file.value);
- }
- defineExpose({
- getFile,
- });
- </script>
- <style lang="scss" scoped>
- .updata-img {
- border-radius: 8px;
- background: rgba(255, 255, 255, 1);
- height: 100px;
- padding: 16px;
- display: flex;
- align-content: center;
- justify-content: space-between;
- .updata-title-box {
- display: flex;
- align-content: center;
- flex-direction: column;
- justify-content: space-evenly;
- }
- }
- </style>
|