mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-20 20:39:55 +00:00
refactor(upload): 重构文件上传组件并优化相关逻辑
移除旧的FileUpload和MultiImageUpload组件,统一使用SingleImageUpload组件处理上传 重构SingleImageUpload组件,使用ConfigAPI替代FileAPI,优化上传逻辑和错误处理 更新用户头像上传逻辑,使用UserAPI处理上传并优化交互体验 优化数据库初始化流程,分离数据库操作和Redis相关操作 重构字典数据配置,合并重复的字典类型并更新相关视图组件 修复定时任务控制器参数类型,从Query改为Body 添加ElImageViewer组件类型声明 优化数据库连接错误处理和日志信息
This commit is contained in:
@@ -1,81 +0,0 @@
|
||||
import request from "@/utils/request";
|
||||
|
||||
const FileAPI = {
|
||||
/**
|
||||
* 上传文件
|
||||
*
|
||||
* @param formData
|
||||
*/
|
||||
upload(formData: FormData) {
|
||||
return request<any, FileInfo>({
|
||||
url: "/api/v1/files",
|
||||
method: "post",
|
||||
data: formData,
|
||||
headers: {
|
||||
"Content-Type": "multipart/form-data",
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*/
|
||||
uploadFile(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return request<any, FileInfo>({
|
||||
url: "/api/v1/files",
|
||||
method: "post",
|
||||
data: formData,
|
||||
headers: {
|
||||
"Content-Type": "multipart/form-data",
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
*
|
||||
* @param filePath 文件完整路径
|
||||
*/
|
||||
delete(filePath?: string) {
|
||||
return request({
|
||||
url: "/api/v1/files",
|
||||
method: "delete",
|
||||
params: { filePath },
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 下载文件
|
||||
* @param url
|
||||
* @param fileName
|
||||
*/
|
||||
download(url: string, fileName?: string) {
|
||||
return request({
|
||||
url,
|
||||
method: "get",
|
||||
responseType: "blob",
|
||||
}).then((res) => {
|
||||
const blob = new Blob([res.data]);
|
||||
const a = document.createElement("a");
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
a.href = url;
|
||||
a.download = fileName || "下载文件";
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default FileAPI;
|
||||
|
||||
/**
|
||||
* 文件API类型声明
|
||||
*/
|
||||
export interface FileInfo {
|
||||
/** 文件名 */
|
||||
name: string;
|
||||
/** 文件路径 */
|
||||
url: string;
|
||||
}
|
||||
@@ -10,7 +10,7 @@ export const UserAPI = {
|
||||
},
|
||||
|
||||
uploadCurrentUserAvatar(body: any) {
|
||||
return request<ApiResponse>({
|
||||
return request<ApiResponse<UploadFilePath>>({
|
||||
url: `/system/user/current/avatar/upload`,
|
||||
method: "post",
|
||||
data: body,
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
Vendored
+1
@@ -49,6 +49,7 @@ declare module 'vue' {
|
||||
ElFormItem: typeof import('element-plus/es')['ElFormItem']
|
||||
ElIcon: typeof import('element-plus/es')['ElIcon']
|
||||
ElImage: typeof import('element-plus/es')['ElImage']
|
||||
ElImageViewer: typeof import('element-plus/es')['ElImageViewer']
|
||||
ElInput: typeof import('element-plus/es')['ElInput']
|
||||
ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
|
||||
ElLink: typeof import('element-plus/es')['ElLink']
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
// 图片上传失败的回调处理
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user