若依框架中只有个人中心有上传图片组件,但是这个组件不适用于el-dialog中的el-form表单页面
于是通过elementui重新写了一个上传组件,如图是实现效果
vue代码
<el-dialog :title="title" v-model="find" width="600px" :close-on-click-modal="false" :draggable="true" append-to-body><el-form :model="form" :rules="rules" ref="userRef" label-width="80px"><el-row><el-col :span="12"><el-form-item label="用户名称" prop="nickName"><el-input v-model="form.nickName" placeholder="请输入用户名称" maxlength="30" :disabled="true" /></el-form-item></el-col></el-row><el-row><el-col :span="12"><el-form-item label="登录密码" prop="password"><el-input v-model="form.password" placeholder="请输入登录密码" type="password" maxlength="20" :disabled="true" /></el-form-item></el-col></el-row><el-row><el-col :lg="2" :md="2"><el-form-item label="上传照片"><div class="custom-upload"><el-uploadclass="upload-demo"action="#"style="width: 200px":on-change="handleFileChange":file-list="fileList":auto-upload="false"accept="image/*":disabled="true"><!-- 上传按钮 --><el-button slot="trigger" type="primary" :disabled="true">选择文件<el-icon class="el-icon-upload" v-model="form.avatar"></el-icon></el-button></el-upload><!-- 图片预览 --><img v-if="previewImage" :src="previewImage" alt="Preview" style="max-width: 100%; margin-top: 10px;"></div></el-form-item></el-col></el-row></el-form><template #footer><div class="dialog-footer"><el-button type="primary" @click="submitForm">确 定</el-button><el-button @click="cancel">取 消</el-button></div></template></el-dialog>
js代码
<script setup name="User">
import { uploadImg } from "@/api/system/user"; //这是个人中心上传照片的接口,可以直接拿过来用const previewImage = ref('');
const fileList = ref([]);const data = reactive({form: {},
});const { form } = toRefs(data);/** 处理文件改变事件 */
function handleFileChange(file) {const selectedFile = file.raw;if (selectedFile) {const reader = new FileReader();reader.readAsDataURL(selectedFile);reader.onload = () => {previewImage.value = reader.result;const formData = new FormData();formData.append('avatarfile', selectedFile);uploadImg(formData).then(response => {console.log('上传成功:', response.imgUrl);// 如果需要其他操作,可以在这里进行处理form.value.avatar=response.imgUrl}).catch(error => {console.error('上传失败:', error);});};}fileList.value = [file];
}</script >