refactor(upload): 重构文件上传组件并优化相关逻辑

移除旧的FileUpload和MultiImageUpload组件,统一使用SingleImageUpload组件处理上传
重构SingleImageUpload组件,使用ConfigAPI替代FileAPI,优化上传逻辑和错误处理
更新用户头像上传逻辑,使用UserAPI处理上传并优化交互体验
优化数据库初始化流程,分离数据库操作和Redis相关操作
重构字典数据配置,合并重复的字典类型并更新相关视图组件
修复定时任务控制器参数类型,从Query改为Body
添加ElImageViewer组件类型声明
优化数据库连接错误处理和日志信息
This commit is contained in:
zhangtao
2025-08-05 01:32:48 +08:00
parent ea1f2db086
commit 56d04b4e14
20 changed files with 559 additions and 1447 deletions
@@ -14,7 +14,6 @@
</template>
<script setup lang="ts">
import { defineProps, defineEmits } from 'vue'
// 定义组件属性
defineProps({
@@ -1,276 +0,0 @@
<!-- 文件上传组件 -->
<template>
<div>
<el-upload
v-model:file-list="fileList"
:style="props.style"
:before-upload="handleBeforeUpload"
:http-request="handleUpload"
:on-progress="handleProgress"
:on-success="handleSuccess"
:on-error="handleError"
:accept="props.accept"
:limit="props.limit"
multiple
>
<!-- 上传文件按钮 -->
<el-button type="primary" :disabled="fileList.length >= props.limit">
{{ props.uploadBtnText }}
</el-button>
<!-- 文件列表 -->
<template #file="{ file }">
<div class="el-upload-list__item-info">
<a class="el-upload-list__item-name" @click="handleDownload(file)">
<el-icon><Document /></el-icon>
<span class="el-upload-list__item-file-name">{{ file.name }}</span>
<span class="el-icon--close" @click.stop="handleRemove(file.url!)">
<el-icon><Close /></el-icon>
</span>
</a>
</div>
</template>
</el-upload>
<el-progress
:style="{
display: showProgress ? 'inline-flex' : 'none',
width: '100%',
}"
:percentage="progressPercent"
/>
</div>
</template>
<script lang="ts" setup>
import {
UploadRawFile,
UploadUserFile,
UploadFile,
UploadFiles,
UploadProgressEvent,
UploadRequestOptions,
} from "element-plus";
import FileAPI, { FileInfo } from "@/api/file.api";
const props = defineProps({
/**
* 请求携带的额外参数
*/
data: {
type: Object,
default: () => {
return {};
},
},
/**
* 上传文件的参数名
*/
name: {
type: String,
default: "file",
},
/**
* 文件上传数量限制
*/
limit: {
type: Number,
default: 10,
},
/**
* 单个文件上传大小限制(单位MB)
*/
maxFileSize: {
type: Number,
default: 10,
},
/**
* 上传文件类型
*/
accept: {
type: String,
default: "*",
},
/**
* 上传按钮文本
*/
uploadBtnText: {
type: String,
default: "上传文件",
},
/**
* 样式
*/
style: {
type: Object,
default: () => {
return {
width: "300px",
};
},
},
});
const modelValue = defineModel("modelValue", {
type: [Array] as PropType<FileInfo[]>,
required: true,
default: () => [],
});
const fileList = ref([] as UploadFile[]);
const showProgress = ref(false);
const progressPercent = ref(0);
// 监听 modelValue 转换用于显示的 fileList
watch(
modelValue,
(value) => {
fileList.value = value.map((item) => {
const name = item.name ? item.name : item.url?.substring(item.url.lastIndexOf("/") + 1);
return {
name,
url: item.url,
status: "success",
uid: getUid(),
} as UploadFile;
});
},
{
immediate: true,
}
);
/**
* 上传前校验
*/
function handleBeforeUpload(file: UploadRawFile) {
// 限制文件大小
if (file.size > props.maxFileSize * 1024 * 1024) {
ElMessage.warning("上传文件不能大于" + props.maxFileSize + "M");
return false;
}
return true;
}
/*
* 上传文件
*/
function handleUpload(options: UploadRequestOptions) {
return new Promise((resolve, reject) => {
const file = options.file;
const formData = new FormData();
formData.append(props.name, file);
// 处理附加参数
Object.keys(props.data).forEach((key) => {
formData.append(key, props.data[key]);
});
FileAPI.upload(formData)
.then((data) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}
/**
* 上传进度
*
* @param event
*/
const handleProgress = (event: UploadProgressEvent) => {
progressPercent.value = event.percent;
};
/**
* 上传成功
*/
const handleSuccess = (response: any, uploadFile: UploadFile, files: UploadFiles) => {
ElMessage.success("上传成功");
//只有当状态为success或者fail,代表文件上传全部完成了,失败也算完成
if (
files.every((file: UploadFile) => {
return file.status === "success" || file.status === "fail";
})
) {
const fileInfos = [] as FileInfo[];
files.map((file: UploadFile) => {
if (file.status === "success") {
//只取携带response的才是刚上传的
const res = file.response as FileInfo;
if (res) {
fileInfos.push({ name: res.name, url: res.url } as FileInfo);
}
} else {
//失败上传 从fileList删掉,不展示
fileList.value.splice(
fileList.value.findIndex((e) => e.uid === file.uid),
1
);
}
});
if (fileInfos.length > 0) {
modelValue.value = [...modelValue.value, ...fileInfos];
}
}
};
/**
* 上传失败
*/
const handleError = (_error: any) => {
console.error(_error);
ElMessage.error("上传失败");
};
/**
* 删除文件
*/
function handleRemove(fileUrl: string) {
FileAPI.delete(fileUrl).then(() => {
modelValue.value = modelValue.value.filter((file) => file.url !== fileUrl);
});
}
/**
* 下载文件
*/
function handleDownload(file: UploadUserFile) {
const { url, name } = file;
if (url) {
FileAPI.download(url, name);
}
}
/** 获取一个不重复的id */
function getUid(): number {
// 时间戳左移13位(相当于乘以8192) + 4位随机数
return (Date.now() << 13) | Math.floor(Math.random() * 8192);
}
</script>
<style lang="scss" scoped>
.el-upload-list__item .el-icon--close {
position: absolute;
top: 50%;
right: 5px;
color: var(--el-text-color-regular);
cursor: pointer;
opacity: 0.75;
transform: translateY(-50%);
transition: opacity var(--el-transition-duration);
}
:deep(.el-upload-list) {
margin: 0;
}
:deep(.el-upload-list__item) {
margin: 0;
}
</style>
+11 -2
View File
@@ -7,7 +7,16 @@
<!-- 表单 -->
<el-form ref="importFormRef" style="padding-right: var(--el-dialog-padding-primary)" :model="importFormData" :rules="importFormRules">
<el-form-item label="文件名" prop="files">
<el-upload ref="uploadRef" v-model:file-list="importFormData.files" class="w-full" :accept="props.accept" :drag="true" :limit="props.limit" :auto-upload="false" :on-exceed="handleFileExceed">
<el-upload
ref="uploadRef"
v-model:file-list="importFormData.files"
class="w-full"
:accept="props.accept"
:drag="true"
:limit="props.limit"
:auto-upload="false"
:on-exceed="handleFileExceed"
>
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">
{{ props.dropText || '将文件拖到此处,或' }}
@@ -45,7 +54,7 @@
<script lang="ts" setup>
import { ElMessage, type UploadUserFile } from "element-plus";
import { ref, reactive, defineProps, defineEmits, defineModel } from "vue";
import { ref, reactive } from "vue";
// 定义props
const props = defineProps({
@@ -1,215 +0,0 @@
<!-- 图片上传组件 -->
<template>
<el-upload
v-model:file-list="fileList"
list-type="picture-card"
:before-upload="handleBeforeUpload"
:http-request="handleUpload"
:on-success="handleSuccess"
:on-error="handleError"
:on-exceed="handleExceed"
:accept="props.accept"
:limit="props.limit"
multiple
>
<el-icon><Plus /></el-icon>
<template #file="{ file }">
<div style="width: 100%">
<img class="el-upload-list__item-thumbnail" :src="file.url" />
<span class="el-upload-list__item-actions">
<!-- 预览 -->
<span @click="handlePreviewImage(file.url!)">
<el-icon><View /></el-icon>
</span>
<!-- 删除 -->
<span @click="handleRemove(file.url!)">
<el-icon><Delete /></el-icon>
</span>
</span>
</div>
</template>
</el-upload>
<el-image-viewer
v-if="previewVisible"
:zoom-rate="1.2"
:initial-index="previewImageIndex"
:url-list="modelValue"
@close="handlePreviewClose"
/>
</template>
<script setup lang="ts">
import { UploadRawFile, UploadRequestOptions, UploadUserFile } from "element-plus";
import FileAPI, { FileInfo } from "@/api/file.api";
const props = defineProps({
/**
* 请求携带的额外参数
*/
data: {
type: Object,
default: () => {
return {};
},
},
/**
* 上传文件的参数名
*/
name: {
type: String,
default: "file",
},
/**
* 文件上传数量限制
*/
limit: {
type: Number,
default: 10,
},
/**
* 单个文件的最大允许大小
*/
maxFileSize: {
type: Number,
default: 10,
},
/**
* 上传文件类型
*/
accept: {
type: String,
default: "image/*", // 默认支持所有图片格式 ,如果需要指定格式,格式如下:'.png,.jpg,.jpeg,.gif,.bmp'
},
});
const previewVisible = ref(false); // 是否显示预览
const previewImageIndex = ref(0); // 预览图片的索引
const modelValue = defineModel("modelValue", {
type: [Array] as PropType<string[]>,
default: () => [],
});
const fileList = ref<UploadUserFile[]>([]);
/**
* 删除图片
*/
function handleRemove(imageUrl: string) {
FileAPI.delete(imageUrl).then(() => {
const index = modelValue.value.indexOf(imageUrl);
if (index !== -1) {
// 直接修改数组避免触发整体更新
modelValue.value.splice(index, 1);
fileList.value.splice(index, 1); // 同步更新 fileList
}
});
}
/**
* 上传前校验
*/
function handleBeforeUpload(file: UploadRawFile) {
// 校验文件类型:虽然 accept 属性限制了用户在文件选择器中可选的文件类型,但仍需在上传时再次校验文件实际类型,确保符合 accept 的规则
const acceptTypes = props.accept.split(",").map((type) => type.trim());
// 检查文件格式是否符合 accept
const isValidType = acceptTypes.some((type) => {
if (type === "image/*") {
// 如果是 image/*,检查 MIME 类型是否以 "image/" 开头
return file.type.startsWith("image/");
} else if (type.startsWith(".")) {
// 如果是扩展名 (.png, .jpg),检查文件名是否以指定扩展名结尾
return file.name.toLowerCase().endsWith(type);
} else {
// 如果是具体的 MIME 类型 (image/png, image/jpeg),检查是否完全匹配
return file.type === type;
}
});
if (!isValidType) {
ElMessage.warning(`上传文件的格式不正确,仅支持:${props.accept}`);
return false;
}
// 限制文件大小
if (file.size > props.maxFileSize * 1024 * 1024) {
ElMessage.warning("上传图片不能大于" + props.maxFileSize + "M");
return false;
}
return true;
}
/*
* 上传文件
*/
function handleUpload(options: UploadRequestOptions) {
return new Promise((resolve, reject) => {
const file = options.file;
const formData = new FormData();
formData.append(props.name, file);
// 处理附加参数
Object.keys(props.data).forEach((key) => {
formData.append(key, props.data[key]);
});
FileAPI.upload(formData)
.then((data) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}
/**
* 上传文件超出限制
*/
function handleExceed() {
ElMessage.warning("最多只能上传" + props.limit + "张图片");
}
/**
* 上传成功回调
*/
const handleSuccess = (fileInfo: FileInfo, uploadFile: UploadUserFile) => {
ElMessage.success("上传成功");
const index = fileList.value.findIndex((file) => file.uid === uploadFile.uid);
if (index !== -1) {
fileList.value[index].url = fileInfo.url;
fileList.value[index].status = "success";
modelValue.value[index] = fileInfo.url;
}
};
/**
* 上传失败回调
*/
const handleError = (error: any) => {
console.log("handleError");
ElMessage.error("上传失败: " + error.message);
};
/**
* 预览图片
*/
const handlePreviewImage = (imageUrl: string) => {
previewImageIndex.value = modelValue.value.findIndex((url) => url === imageUrl);
previewVisible.value = true;
};
/**
* 关闭预览
*/
const handlePreviewClose = () => {
previewVisible.value = false;
};
onMounted(() => {
fileList.value = modelValue.value.map((url) => ({ url }) as UploadUserFile);
});
</script>
<style lang="scss" scoped></style>
@@ -8,8 +8,6 @@
:accept="props.accept"
:before-upload="handleBeforeUpload"
:http-request="handleUpload"
:on-success="onSuccess"
:on-error="onError"
>
<template #default>
<el-image v-if="modelValue" :src="modelValue" />
@@ -36,8 +34,8 @@
</template>
<script setup lang="ts">
import { UploadRawFile, UploadRequestOptions, ElImageViewer } from "element-plus";
import FileAPI, { FileInfo } from "@/api/file.api";
import { UploadRawFile, UploadRequestOptions, ElMessage } from "element-plus";
import ConfigAPI from '@/api/system/config';
const props = defineProps({
/**
@@ -95,10 +93,10 @@ const modelValue = defineModel("modelValue", {
* 定义组件触发的事件
*/
const emit = defineEmits<{
(e: 'success', fileInfo: FileInfo): void;
(e: 'success', fileInfo: UploadFilePath): void;
(e: 'error', error: any): void;
(e: 'input', value: string): void;
(e: 'onSuccess', fileInfo: FileInfo): void;
(e: 'onSuccess', fileInfo: UploadFilePath): void;
(e: 'onError', error: any): void;
}>();
@@ -139,26 +137,34 @@ function handleBeforeUpload(file: UploadRawFile) {
/*
* 上传图片
*/
function handleUpload(options: UploadRequestOptions) {
return new Promise((resolve, reject) => {
async function handleUpload(options: UploadRequestOptions) {
try {
const file = options.file;
const formData = new FormData();
formData.append(props.name, file);
// 处理附加参数
Object.keys(props.data).forEach((key) => {
formData.append(key, props.data[key]);
});
for (const [key, value] of Object.entries(props.data)) {
formData.append(key, String(value));
}
FileAPI.upload(formData)
.then((data) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
const response = await ConfigAPI.uploadFile(formData);
if (response.data.code === 0 && response.data) {
const fileInfo: UploadFilePath = response.data.data;
// 调用成功回调
onSuccess(fileInfo);
return fileInfo;
} else {
const errorMsg = response.data.msg || '上传失败';
ElMessage.error(errorMsg);
throw new Error(errorMsg);
}
} catch (error) {
onError(error instanceof Error ? error : new Error(String(error)));
throw error;
}
}
/**
@@ -186,18 +192,20 @@ function handlePreview(imagePath: string) {
*
* @param fileInfo 上传成功后的文件信息
*/
const onSuccess = (fileInfo: FileInfo) => {
ElMessage.success("上传成功");
const onSuccess = (fileInfo: UploadFilePath) => {
modelValue.value = fileInfo.file_url; // 更新绑定的值为文件URL
emit('onSuccess', fileInfo); // 触发 onSuccess 事件
emit('success', fileInfo); // 触发 success 事件
emit('input', fileInfo.file_url); // 触发 input 事件,通知父组件值变化
};
/**
* 上传失败回调
*/
const onError = (error: any) => {
console.log("onError");
ElMessage.error("上传失败: " + error.message);
console.log("onError", error);
emit('onError', error); // 触发 onError 事件
emit('error', error); // 触发 error 事件
};
</script>