refactor:【ele】重新封装上传组件

This commit is contained in:
puhui999
2025-09-26 10:52:30 +08:00
parent c64c770f54
commit f0fbaf45f4
4 changed files with 269 additions and 282 deletions

View File

@@ -1,261 +1,282 @@
<script lang="ts" setup>
import type {
UploadFile,
UploadProgressEvent,
UploadRequestOptions,
UploadInstance,
UploadProps,
UploadRawFile,
UploadUserFile,
} from 'element-plus';
import type { AxiosResponse } from '@vben/request';
import { ref, watch } from 'vue';
import type { AxiosProgressEvent } from '#/api/infra/file';
import { IconifyIcon } from '@vben/icons';
import { isString } from '@vben/utils';
import { ref, toRefs, watch } from 'vue';
import { ElButton, ElLink, ElMessage, ElUpload } from 'element-plus';
import { CloudUpload } from '@vben/icons';
import { $t } from '@vben/locales';
import { isFunction, isObject, isString } from '@vben/utils';
import { ElButton, ElMessage, ElUpload } from 'element-plus';
import { checkFileType } from './helper';
import { UploadResultStatus } from './typing';
import { useUpload, useUploadType } from './use-upload';
import { useUpload } from './use-upload';
defineOptions({ name: 'FileUpload', inheritAttrs: false });
const props = withDefaults(
defineProps<{
// 根据后缀,或者其他
accept?: string[];
api?: (
file: File,
onUploadProgress?: AxiosProgressEvent,
) => Promise<AxiosResponse<any>>;
// 上传的目录
autoUpload?: boolean;
directory?: string;
disabled?: boolean;
helpText?: string;
// 最大数量的文件Infinity不限制
maxNumber?: number;
// 文件最大多少MB
maxSize?: number;
// 是否支持多选
multiple?: boolean;
// support xxx.xxx.xx
resultField?: string;
// 是否显示下面的描述
showDescription?: boolean;
value?: string | string[];
drag?: boolean;
fileSize?: number;
fileType?: string[];
isShowTip?: boolean;
limit?: number;
modelValue: string | string[];
}>(),
{
value: () => [],
directory: undefined,
disabled: false,
helpText: '',
maxSize: 2,
maxNumber: 1,
accept: () => [],
multiple: false,
api: undefined,
resultField: '',
showDescription: false,
fileType: () => ['doc', 'xls', 'ppt', 'txt', 'pdf'], // 文件类型, 例如['png', 'jpg', 'jpeg']
fileSize: 5, // 大小限制(MB)
limit: 5, // 数量限制
autoUpload: true, // 自动上传
drag: false, // 拖拽上传
isShowTip: true, // 是否显示提示
disabled: false, // 是否禁用上传组件 ==> 非必传(默认为 false
directory: undefined, // 上传目录 ==> 非必传(默认为 undefined
},
);
const emit = defineEmits(['change', 'update:value', 'delete', 'returnText']);
const { accept, helpText, maxNumber, maxSize } = toRefs(props);
const isInnerOperate = ref<boolean>(false);
const { getStringAccept } = useUploadType({
acceptRef: accept,
helpTextRef: helpText,
maxNumberRef: maxNumber,
maxSizeRef: maxSize,
});
const emit = defineEmits(['update:modelValue']);
// ========== 上传相关 ==========
const uploadRef = ref<UploadInstance>();
const uploadList = ref<UploadUserFile[]>([]);
const fileList = ref<UploadUserFile[]>([]);
const isLtMsg = ref<boolean>(true); // 文件大小错误提示
const isActMsg = ref<boolean>(true); // 文件类型错误提示
const isFirstRender = ref<boolean>(true); // 是否第一次渲染
const uploadNumber = ref<number>(0);
watch(
() => props.value,
(v) => {
if (isInnerOperate.value) {
isInnerOperate.value = false;
return;
}
let value: string[] = [];
if (v) {
if (Array.isArray(v)) {
value = v;
} else {
value.push(v);
}
fileList.value = value
.map((item, i) => {
if (item && isString(item)) {
return {
uid: -i,
name: item.slice(Math.max(0, item.lastIndexOf('/') + 1)),
status: UploadResultStatus.DONE,
url: item,
} as UploadUserFile;
} else if (item && isObject(item)) {
const file = item as Record<string, any>;
return {
uid: file.uid || -i,
name: file.name || '',
status: UploadResultStatus.DONE,
url: file.url,
response: file.response,
percentage: file.percentage,
size: file.size,
} as UploadUserFile;
}
return null;
})
.filter(Boolean) as UploadUserFile[];
}
if (!isFirstRender.value) {
emit('change', value);
isFirstRender.value = false;
}
},
{
immediate: true,
deep: true,
},
);
const { uploadUrl, httpRequest }: any = useUpload(props.directory);
const handleRemove = async (file: UploadFile) => {
if (fileList.value) {
const index = fileList.value.findIndex((item) => item.uid === file.uid);
index !== -1 && fileList.value.splice(index, 1);
const value = getValue();
isInnerOperate.value = true;
emit('update:value', value);
emit('change', value);
emit('delete', file);
}
/** httpRequest 适配 ele */
const httpRequest0 = (options: UploadRequestOptions) => {
return httpRequest(options.file);
};
const beforeUpload = async (file: File) => {
const fileContent = await file.text();
emit('returnText', fileContent);
const { maxSize, accept } = props;
const isAct = checkFileType(file, accept);
if (!isAct) {
ElMessage.error($t('ui.upload.acceptUpload', [accept]));
isActMsg.value = false;
// 防止弹出多个错误提示
setTimeout(() => (isActMsg.value = true), 1000);
// 文件上传之前判断
const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
if (fileList.value.length >= props.limit) {
ElMessage.error(`上传文件数量不能超过${props.limit}个!`);
return false;
}
const isLt = file.size / 1024 / 1024 > maxSize;
if (isLt) {
ElMessage.error($t('ui.upload.maxSizeMultiple', [maxSize]));
isLtMsg.value = false;
// 防止弹出多个错误提示
setTimeout(() => (isLtMsg.value = true), 1000);
let fileExtension = '';
// eslint-disable-next-line unicorn/prefer-includes
if (file.name.lastIndexOf('.') > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
}
const isImg = props.fileType.some((type: string) => {
// eslint-disable-next-line unicorn/prefer-includes
if (file.type.indexOf(type) > -1) return true;
// eslint-disable-next-line unicorn/prefer-includes
return !!(fileExtension && fileExtension.indexOf(type) > -1);
});
const isLimit = file.size < props.fileSize * 1024 * 1024;
if (!isImg) {
ElMessage.error(`文件格式不正确, 请上传${props.fileType.join('/')}格式!`);
return false;
}
if (!isLimit) {
ElMessage.error(`上传文件大小不能超过${props.fileSize}MB!`);
return false;
}
ElMessage.success('正在上传文件,请稍候...');
// 只有在验证通过后才增加计数器
uploadNumber.value++;
return true;
};
async function customRequest(options: UploadRequestOptions) {
let { api } = props;
if (!api || !isFunction(api)) {
api = useUpload(props.directory).httpRequest;
// 文件上传成功
const handleFileSuccess: UploadProps['onSuccess'] = (url: any): void => {
ElMessage.success('上传成功');
// 删除自身
const index = fileList.value.findIndex((item: any) => item.response === url);
fileList.value.splice(index, 1);
uploadList.value.push({ name: url, url });
if (uploadList.value.length === uploadNumber.value) {
fileList.value.push(...uploadList.value);
uploadList.value = [];
uploadNumber.value = 0;
emitUpdateModelValue();
}
try {
// 上传文件
const progressEvent: AxiosProgressEvent = (e) => {
const percent = Math.trunc((e.loaded / e.total!) * 100);
const progressEvent: UploadProgressEvent = {
percent,
total: e.total || 0,
loaded: e.loaded || 0,
lengthComputable: true,
target: e.event.target as EventTarget,
bubbles: false,
cancelBubble: false,
cancelable: false,
composed: false,
currentTarget: e.event.target as EventTarget,
defaultPrevented: false,
eventPhase: 0,
isTrusted: true,
returnValue: true,
srcElement: e.event.target as EventTarget,
timeStamp: Date.now(),
type: 'progress',
composedPath: () => [],
initEvent: () => {},
preventDefault: () => {},
stopImmediatePropagation: () => {},
stopPropagation: () => {},
NONE: 0,
CAPTURING_PHASE: 1,
AT_TARGET: 2,
BUBBLING_PHASE: 3,
};
options.onProgress!(progressEvent);
};
const res = await api?.(options.file, progressEvent);
options.onSuccess!(res);
ElMessage.success($t('ui.upload.uploadSuccess'));
};
// 文件数超出提示
const handleExceed: UploadProps['onExceed'] = (): void => {
ElMessage.error(`上传文件数量不能超过${props.limit}个!`);
};
// 上传错误提示
const excelUploadError: UploadProps['onError'] = (): void => {
ElMessage.error('导入数据失败,请您重新上传!');
// 上传失败时减少计数器,避免后续上传被阻塞
uploadNumber.value = Math.max(0, uploadNumber.value - 1);
};
// 删除上传文件
const handleRemove = (file: UploadFile) => {
const index = fileList.value.map((f) => f.name).indexOf(file.name);
if (index !== -1) {
fileList.value.splice(index, 1);
emitUpdateModelValue();
}
};
const handlePreview: UploadProps['onPreview'] = (_) => {
// console.log(uploadFile);
};
// 更新文件
const value = getValue();
isInnerOperate.value = true;
emit('update:value', value);
emit('change', value);
} catch (error: any) {
console.error(error);
options.onError!(error);
}
}
// 监听模型绑定值变动
watch(
() => props.modelValue,
(val: string | string[]) => {
if (!val) {
fileList.value = []; // fix处理掉缓存表单重置后上传组件的内容并没有重置
return;
}
function getValue() {
const list = (fileList.value || [])
.filter((item) => item?.status === UploadResultStatus.DONE)
.map((item: any) => {
if (item?.response && props?.resultField) {
return item?.response;
}
return item?.url || item?.response?.url || item?.response;
});
// add by 芋艿:【特殊】单个文件的情况,获取首个元素,保证返回的是 String 类型
if (props.maxNumber === 1) {
return list.length > 0 ? list[0] : '';
fileList.value = []; // 保障数据为空
// 情况1字符串
if (isString(val)) {
fileList.value.push(
...val.split(',').map((url) => ({
// eslint-disable-next-line unicorn/prefer-string-slice
name: url.substring(url.lastIndexOf('/') + 1),
url,
})),
);
return;
}
// 情况2数组
fileList.value.push(
...(val as string[]).map((url) => ({
// eslint-disable-next-line unicorn/prefer-string-slice
name: url.substring(url.lastIndexOf('/') + 1),
url,
})),
);
},
{ immediate: true, deep: true },
);
// 发送文件链接列表更新
const emitUpdateModelValue = () => {
// 情况1数组结果
let result: string | string[] = fileList.value.map((file) => file.url!);
// 情况2逗号分隔的字符串
if (props.limit === 1 || isString(props.modelValue)) {
result = result.join(',');
}
return list;
}
emit('update:modelValue', result);
};
</script>
<template>
<div>
<div v-if="!disabled" class="upload-file">
<ElUpload
v-bind="$attrs"
ref="uploadRef"
v-model:file-list="fileList"
:accept="getStringAccept"
:action="uploadUrl"
:auto-upload="autoUpload"
:before-upload="beforeUpload"
:http-request="customRequest"
:disabled="disabled"
:limit="maxNumber"
:multiple="multiple"
list-type="text"
:drag="drag"
:http-request="httpRequest0"
:limit="props.limit"
:multiple="props.limit > 1"
:on-error="excelUploadError"
:on-exceed="handleExceed"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="handleFileSuccess"
:show-file-list="true"
class="upload-file-uploader"
name="file"
>
<div v-if="fileList && fileList.length < maxNumber">
<ElButton>
<CloudUpload />
{{ $t('ui.upload.upload') }}
</ElButton>
</div>
<div v-if="showDescription" class="mt-2 text-xs text-gray-500">
{{ getStringAccept }}
</div>
<ElButton type="primary">
<IconifyIcon icon="ep:upload-filled" />
选取文件
</ElButton>
<template v-if="isShowTip" #tip>
<div style="font-size: 8px">
大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
</div>
<div style="font-size: 8px">
格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b> 的文件
</div>
</template>
<template #file="row">
<div class="flex items-center">
<span>{{ row.file.name }}</span>
<div class="ml-10px">
<ElLink
:href="row.file.url"
:underline="false"
download
target="_blank"
type="primary"
>
下载
</ElLink>
</div>
<div class="ml-10px">
<ElButton link type="danger" @click="handleRemove(row.file)">
删除
</ElButton>
</div>
</div>
</template>
</ElUpload>
</div>
<!-- 上传操作禁用时 -->
<div v-if="disabled" class="upload-file">
<div
v-for="(file, index) in fileList"
:key="index"
class="file-list-item flex items-center"
>
<span>{{ file.name }}</span>
<div class="ml-10px">
<ElLink
:href="file.url"
:underline="false"
download
target="_blank"
type="primary"
>
下载
</ElLink>
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
.upload-file-uploader {
margin-bottom: 5px;
}
:deep(.upload-file-list .el-upload-list__item) {
position: relative;
margin-bottom: 10px;
line-height: 2;
border: 1px solid #e4e7ed;
}
:deep(.el-upload-list__item-file-name) {
max-width: 250px;
}
:deep(.upload-file-list .ele-upload-list__item-content) {
display: flex;
justify-content: space-between;
align-items: center;
color: inherit;
}
:deep(.ele-upload-list__item-content-action .el-link) {
margin-right: 10px;
}
.file-list-item {
border: 1px dashed var(--el-border-color-darker);
border-radius: 8px;
}
</style>

View File

@@ -79,17 +79,17 @@ export function useUploadType({
}
// TODO @芋艿:目前保持和 admin-vue3 一致,后续可能重构
export const useUpload = (directory?: string) => {
export function useUpload(directory?: string) {
// 后端上传地址
const uploadUrl = getUploadUrl();
// 是否使用前端直连上传
const isClientUpload =
UPLOAD_TYPE.CLIENT === import.meta.env.VITE_UPLOAD_TYPE;
// 重写ElUpload上传方法
const httpRequest = async (
async function httpRequest(
file: File,
onUploadProgress?: AxiosProgressEvent,
) => {
) {
// 模式一:前端上传
if (isClientUpload) {
// 1.1 生成文件名称
@@ -113,20 +113,20 @@ export const useUpload = (directory?: string) => {
// 模式二:后端上传
return uploadFile({ file, directory }, onUploadProgress);
}
};
}
return {
uploadUrl,
httpRequest,
};
};
}
/**
* 获得上传 URL
*/
export const getUploadUrl = (): string => {
export function getUploadUrl(): string {
return `${apiURL}/infra/file/upload`;
};
}
/**
* 创建文件信息
@@ -134,7 +134,10 @@ export const getUploadUrl = (): string => {
* @param vo 文件预签名信息
* @param file 文件
*/
function createFile0(vo: InfraFileApi.FilePresignedUrlRespVO, file: File) {
function createFile0(
vo: InfraFileApi.FilePresignedUrlRespVO,
file: File,
): InfraFileApi.File {
const fileVO = {
configId: vo.configId,
url: vo.url,
@@ -148,10 +151,18 @@ function createFile0(vo: InfraFileApi.FilePresignedUrlRespVO, file: File) {
}
/**
* 生成文件名称
* 生成文件名称使用算法SHA256
*
* @param file 要上传的文件
*/
async function generateFileName(file: File) {
// // 读取文件内容
// const data = await file.arrayBuffer();
// const wordArray = CryptoJS.lib.WordArray.create(data);
// // 计算SHA256
// const sha256 = CryptoJS.SHA256(wordArray).toString();
// // 拼接后缀
// const ext = file.name.slice(Math.max(0, file.name.lastIndexOf('.')));
// return `${sha256}${ext}`;
return file.name;
}

View File

@@ -9,7 +9,7 @@ export function useFormSchema(): VbenFormSchema[] {
{
fieldName: 'file',
label: '文件上传',
component: 'Upload',
component: 'FileUpload',
componentProps: {
placeholder: '请选择要上传的文件',
},

View File

@@ -1,19 +1,19 @@
<script lang="ts" setup>
import type { UploadRawFile } from 'element-plus';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage, ElUpload } from 'element-plus';
import { isEmpty } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { useUpload } from '#/components/upload/use-upload';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const [Form, formApi] = useVbenForm({
const [Modal, modalApi] = useVbenModal({
showConfirmButton: false,
showCancelButton: false,
});
const [Form] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
@@ -25,64 +25,19 @@ const [Form, formApi] = useVbenForm({
layout: 'horizontal',
schema: useFormSchema().map((item) => ({ ...item, label: '' })), // 去除label
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
handleValuesChange: (values) => {
if (isEmpty(values)) {
return;
}
modalApi.lock();
// 提交表单
const data = await formApi.getValues();
try {
await useUpload().httpRequest(data.file);
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
// 上传成功关闭 modal
modalApi.close();
emit('success');
},
});
/** 上传前 */
function beforeUpload(file: UploadRawFile) {
// TODO @puhui999【bug】这个上传功能有点问题。报文件不存在
formApi.setFieldValue('file', file);
return false;
}
</script>
<template>
<Modal title="上传图片">
<Form class="mx-4">
<template #file>
<div class="w-full">
<!-- 上传区域 -->
<ElUpload
class="upload-demo"
drag
:auto-upload="false"
:limit="1"
accept=".jpg,.png,.gif,.webp"
:before-upload="beforeUpload"
list-type="picture-card"
>
<div class="el-upload__text">
<p>
<i class="el-icon-upload text-2xl"></i>
</p>
<p>点击或拖拽文件到此区域上传</p>
<p class="text-sm text-gray-500">
支持 .jpg.png.gif.webp 格式图片文件
</p>
</div>
</ElUpload>
</div>
</template>
</Form>
<Modal title="上传文件">
<Form class="mx-4" />
</Modal>
</template>