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
+79 -13
View File
@@ -23,19 +23,20 @@
/>
<el-upload
ref="uploadRef"
class="el-upload"
v-model:file-list="fileList"
name="avatar"
name="file"
:show-file-list="false"
:before-upload="handleBeforeUpload"
:on-success="handleUploadSuccess"
:http-request="handleUpload"
:disabled="loading"
:limit="1"
:auto-upload="false"
action="/api/upload/avatar"
@change="handleFileChange"
>
<template #trigger>
<el-button type="primary" :icon="Camera" class="upload-trigger" />
<el-button type="primary" :icon="Camera" class="upload-trigger"/>
</template>
</el-upload>
</div>
@@ -197,12 +198,14 @@
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import type { FormInstance, UploadRequestOptions, UploadFile } from 'element-plus'
import UserAPI, { type InfoFormState, type PasswordFormState } from '@/api/system/user';
import { useUserStore, useDictStore } from "@/store";
import { useUserStoreHook } from "@/store/modules/user.store";
import { Camera } from '@element-plus/icons-vue';
import { ElUpload, ElMessage } from 'element-plus';
import { useI18n } from "vue-i18n";
import { nextTick } from 'vue';
import router from "@/router";
const { t } = useI18n();
@@ -245,27 +248,88 @@ const passwordFormState = reactive<PasswordFormState>({
// 头像上传处理优化
const fileList = ref<any[]>([]);
const uploadRef = ref<InstanceType<typeof ElUpload>>();
// 文件上传前校验
const handleBeforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/');
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isImage) {
ElMessage.error('只能上传图片文件');
return false;
}
if (!isLt2M) {
ElMessage.error('上传图片大小不能超过 2MB!');
return false;
}
return true;
};
// 上传成功回调
const handleUploadSuccess = (response: any) => {
updateAvatar(response.data.file_url);
ElMessage.success('头像上传成功');
// 自定义上传处理
const handleUpload = async (options: UploadRequestOptions) => {
try {
const file = options.file;
const formData = new FormData();
formData.append('file', file);
const response = await UserAPI.uploadCurrentUserAvatar(formData);
if (response.data.code === 0 && response.data.data) {
const fileUrl = response.data.data.file_url;
updateAvatar(fileUrl);
options.onSuccess(response);
} else {
const errorMsg = response.data.msg || '上传失败';
ElMessage.error(errorMsg);
options.onError({
...new Error(errorMsg),
status: response.status || 500,
method: 'POST',
url: '/system/user/current/avatar/upload'
});
}
} catch (error) {
ElMessage.error('头像上传失败,请重试');
const errorObj = error instanceof Error ? error : new Error(String(error));
options.onError({
...errorObj,
status: 500,
method: 'POST',
url: '/system/user/current/avatar/upload'
});
console.error('Upload error:', error);
}
};
// 处理文件选择变化
const handleFileChange = (file: UploadFile, files: UploadFile[]) => {
// 当有新文件被添加且状态为ready时触发上传
if (file) {
// 更新文件列表
fileList.value = [...files];
// 提交上传
if (uploadRef.value) {
uploadRef.value.submit();
}
}
};
// 更新头像信息
const updateAvatar = (fileUrl: string) => {
infoFormState.avatar = fileUrl;
fileList.value = [{ url: fileUrl }];
if (fileUrl) {
// 更新头像状态
infoFormState.avatar = fileUrl;
// 更新文件列表
fileList.value = [{ url: fileUrl }];
// 确保DOM正确更新
nextTick(() => {
console.log('头像已更新:', infoFormState.avatar);
});
} else {
ElMessage.error('无效的头像URL');
console.error('Invalid fileUrl:', fileUrl);
}
};
@@ -353,11 +417,13 @@ const initPasswordForm = () => {
const handleSave = async () => {
try {
infoSubmitting.value = true;
infoFormState.avatar = infoFormState.avatar;
const response = await UserAPI.updateCurrentUserInfo(infoFormState);
// 确保avatar字段被正确处理
const response = await UserAPI.updateCurrentUserInfo({...infoFormState});
await userStore.setUserInfo(response.data.data);
ElMessage.success('保存成功');
} catch (error) {
console.error(error);
ElMessage.error('保存失败,请重试');
} finally {
infoSubmitting.value = false;
}
+1 -1
View File
@@ -235,7 +235,7 @@ defineOptions({
inheritAttrs: false,
});
import { ref, reactive, onMounted, defineEmits } from "vue";
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { ResultEnum } from "@/enums/api/result.enum";
import ExampleAPI, { ExampleTable, ExampleForm, ExamplePageQuery } from "@/api/demo/example";
+9 -9
View File
@@ -145,17 +145,17 @@
</el-table-column>
<el-table-column label="触发器" prop="trigger" min-width="100">
<template #default="scope">
{{ (dictStore.getDictLabel('sys_job_trigger',scope.row.trigger) as any)?.dict_label || scope.row.trigger }}
{{ (dictStore.getDictLabel('sys_job_trigger',scope.row.trigger) as any)?.dict_label }}
</template>
</el-table-column>
<el-table-column label="存储器" prop="jobstore" min-width="120">
<template #default="scope">
{{ (dictStore.getDictLabel('sys_job_store',scope.row.jobstore) as any)?.dict_label || scope.row.jobstore }}
{{ (dictStore.getDictLabel('sys_job_store',scope.row.jobstore) as any)?.dict_label }}
</template>
</el-table-column>
<el-table-column label="执行器" prop="executor" min-width="100">
<template #default="scope">
{{ (dictStore.getDictLabel('sys_job_executor',scope.row.executor) as any)?.dict_label || scope.row.executor }}
{{ (dictStore.getDictLabel('sys_job_executor',scope.row.executor) as any)?.dict_label }}
</template>
</el-table-column>
<el-table-column label="并发执行" prop="coalesce" min-width="100">
@@ -224,12 +224,12 @@
<el-dropdown-menu>
<el-dropdown-item
icon="Check"
@click="handleOption(scope.row, 1)"
@click="handleOption(scope.row.id, 1)"
>暂停</el-dropdown-item
>
<el-dropdown-item
icon="CircleClose"
@click="handleOption(scope.row, 2)"
@click="handleOption(scope.row.id, 2)"
>恢复</el-dropdown-item
>
</el-dropdown-menu>
@@ -267,16 +267,16 @@
detailFormData.name
}}</el-descriptions-item>
<el-descriptions-item label="任务函数" :span="2">{{
detailFormData.func
(detailFormData.func ? dictStore.getDictLabel('sys_job_function', detailFormData.func) as any : undefined)?.dict_label || detailFormData.func
}}</el-descriptions-item>
<el-descriptions-item label="存储器" :span="2">{{
detailFormData.jobstore
(detailFormData.jobstore ? dictStore.getDictLabel('sys_job_store', detailFormData.jobstore) as any : undefined)?.dict_label || detailFormData.jobstore
}}</el-descriptions-item>
<el-descriptions-item label="执行器" :span="2">{{
detailFormData.executor
(detailFormData.executor ? dictStore.getDictLabel('sys_job_executor', detailFormData.executor) as any : undefined)?.dict_label || detailFormData.executor
}}</el-descriptions-item>
<el-descriptions-item label="触发器" :span="2">{{
detailFormData.trigger
(detailFormData.trigger ? dictStore.getDictLabel('sys_job_trigger', detailFormData.trigger) as any : undefined)?.dict_label || detailFormData.trigger
}}</el-descriptions-item>
<el-descriptions-item label="位置参数" :span="2">{{
detailFormData.args
@@ -27,7 +27,8 @@
:data="{ type: key }"
:name="'file'"
:max-file-size="item.maxFileSize"
@on-success="(fileInfo: any) => handleUploadSuccess(fileInfo, key)"
:file-list="fileLists[key] || []"
@on-success="(fileInfo: UploadFilePath) => handleUploadSuccess(fileInfo, key)"
@on-error="handleUploadError"
@input="markModified(key)"
/>
@@ -49,11 +50,17 @@ import { ref, reactive, onMounted, computed } from 'vue';
import ConfigAPI, { type ConfigTable } from '@/api/system/config';
import { useConfigStore } from "@/store";
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import SingleImageUpload from '@/components/Upload/SingleImageUpload.vue';
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";
// 文件列表类型定义
interface FileListItem {
url: string;
}
const appStore = useAppStore();
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "500px" : "90%"));
@@ -72,7 +79,7 @@ const configState = reactive<ConfigTable>({
});
// 存储文件上传列表
const fileLists = reactive<Record<string, any[]>>({});
const fileLists = reactive<Record<string, FileListItem[]>>({});
// 记录修改过的字段
const modifiedFields = reactive<Record<string, boolean>>({});
@@ -91,20 +98,24 @@ const submitChanges = async () => {
if (keysToSubmit.length === 0) return;
try {
for (const key of keysToSubmit) {
// 并行处理所有修改请求,提高性能
const updatePromises = keysToSubmit.map(key => {
const item = systemConfigs.value[key as keyof typeof systemConfigs.value] || logoConfigs.value[key as keyof typeof logoConfigs.value];
if (item) {
await ConfigAPI.updateConfig({ ...item });
}
}
return item ? ConfigAPI.updateConfig({ ...item }) : Promise.resolve();
});
await Promise.all(updatePromises);
ElMessage.success('保存成功');
// 清除已提交的修改标记
for (const key of keysToSubmit) {
keysToSubmit.forEach(key => {
delete modifiedFields[key];
}
});
} catch (error) {
console.error('保存失败:', error);
ElMessage.error('保存失败');
// 提供更详细的错误信息
const errorMessage = error instanceof Error ? error.message : '更新配置时发生错误';
ElMessage.error(`保存失败:${errorMessage}`);
}
};
@@ -152,12 +163,27 @@ const logoConfigs = computed(() => ({
}));
// 图片上传成功的回调处理
const handleUploadSuccess = (fileInfo: any, type: string) => {
const handleUploadSuccess = (fileInfo: UploadFilePath, type: string) => {
// 使用正确的file_url属性
const fileUrl = fileInfo.file_url;
// 更新store中的数据
if (type in configStore.configData) {
configStore.configData[type as keyof typeof configStore.configData].config_value = fileInfo.url;
configStore.configData[type as keyof typeof configStore.configData].config_value = fileUrl;
}
fileLists[type] = [{ url: fileInfo.url }];
ElMessage.success('上传成功');
// 更新对应的item.config_value,确保v-model绑定生效
if (type in systemConfigs.value) {
systemConfigs.value[type as keyof typeof systemConfigs.value].config_value = fileUrl;
} else if (type in logoConfigs.value) {
logoConfigs.value[type as keyof typeof logoConfigs.value].config_value = fileUrl;
}
// 更新文件列表
fileLists[type] = [{ url: fileUrl }];
// 标记为已修改
markModified(type);
};
// 图片上传失败的回调处理
+22 -7
View File
@@ -9,8 +9,12 @@
</el-form-item>
<el-form-item prop="notice_type" label="类型">
<el-select v-model="queryFormData.notice_type" placeholder="请选择类型" style="width: 167.5px" clearable>
<el-option value="1" label="通知" />
<el-option value="2" label="公告" />
<el-option
v-for="item in dictStore.getDictArray('sys_notice_type')"
:key="item.dict_value"
:value="item.dict_value"
:label="item.dict_label"
/>
</el-select>
</el-form-item>
<el-form-item prop="status" label="状态">
@@ -126,7 +130,7 @@
<el-table-column v-if="tableColumns.find(col => col.prop === 'notice_type')?.show" label="类型" prop="notice_type" min-width="80">
<template #default="scope">
<el-tag :type="scope.row.notice_type === '1' ? 'primary' : 'warning'">
{{ scope.row.notice_type === '1' ? "通知" : "公告" }}
{{ (scope.row.notice_type ? dictStore.getDictLabel('sys_notice_type', scope.row.notice_type) as any : undefined)?.dict_label || scope.row.notice_type }}
</el-tag>
</template>
</el-table-column>
@@ -165,7 +169,7 @@
</el-descriptions-item>
<el-descriptions-item label="类型" :span="2">
<el-tag :type="detailFormData.notice_type === '1' ? 'primary' : 'warning'">
{{ detailFormData.notice_type === '1' ? '通知' : '公告' }}
{{ (detailFormData.notice_type ? dictStore.getDictLabel('sys_notice_type', detailFormData.notice_type) as any : undefined)?.dict_label || detailFormData.notice_type }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="状态" :span="2">
@@ -198,8 +202,12 @@
</el-form-item>
<el-form-item label="类型" prop="notice_type">
<el-select v-model="formData.notice_type" placeholder="请选择类型" clearable>
<el-option value="1" label="公告" />
<el-option value="2" label="通知" />
<el-option v-for="item in dictStore.getDictArray('sys_notice_type')"
:key="item.dict_value"
:value="item.dict_value"
:label="item.dict_label"
/>
</el-select>
</el-form-item>
<el-form-item label="状态" prop="status">
@@ -236,6 +244,9 @@
</template>
<script setup lang="ts">
import { useDictStore } from "@/store/index";
const dictStore = useDictStore();
defineOptions({
name: "Notice",
inheritAttrs: false,
@@ -530,7 +541,11 @@ async function handleMoreClick(status: boolean) {
}
}
onMounted(() => {
onMounted(async () => {
// 加载字典数据
await dictStore.getDict(['sys_notice_type']);
// 加载表格数据
loadingData();
});
</script>