feat: 新增文件上传组件

This commit is contained in:
xlsea 2025-04-25 00:59:58 +08:00
parent 03f408f552
commit 15acc1ff68
12 changed files with 400 additions and 98 deletions

View File

@ -0,0 +1,155 @@
<script setup lang="ts">
import { useAttrs } from 'vue';
import type { UploadFileInfo, UploadProps } from 'naive-ui';
import { fetchBatchDeleteOss } from '@/service/api/system/oss';
import { getToken } from '@/store/modules/auth/shared';
import { getServiceBaseURL } from '@/utils/service';
defineOptions({
name: 'FileUpload'
});
interface Props {
action?: string;
showTip?: boolean;
max?: number;
accept?: string;
fileSize?: number;
uploadType?: 'file' | 'image';
}
const props = withDefaults(defineProps<Props>(), {
action: `/resource/oss/upload`,
showTip: true,
max: 5,
accept: '.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.pdf',
fileSize: 5,
uploadType: 'file'
});
const attrs: UploadProps = useAttrs();
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);
const headers: Record<string, string> = {
Authorization: `Bearer ${getToken()}`,
clientid: import.meta.env.VITE_APP_CLIENT_ID!
};
function beforeUpload(options: { file: UploadFileInfo; fileList: UploadFileInfo[] }) {
const { file } = options;
//
if (props.accept) {
const fileName = file.name.split('.');
const fileExt = `.${fileName[fileName.length - 1]}`;
const isTypeOk = props.accept.split(',')?.includes(fileExt);
if (!isTypeOk) {
window.$message?.error(`文件格式不正确, 请上传 ${props.accept} 格式文件!`);
return false;
}
}
//
if (file.name.includes(',')) {
window.$message?.error('文件名不正确,不能包含英文逗号!');
return false;
}
//
if (props.fileSize && file.file?.size) {
const isLt = file.file?.size / 1024 / 1024 < props.fileSize;
if (!isLt) {
window.$message?.error(`上传文件大小不能超过 ${props.fileSize} MB!`);
return false;
}
}
return true;
}
function isErrorState(xhr: XMLHttpRequest) {
const responseText = xhr?.responseText;
const response = JSON.parse(responseText);
return response.code !== 200;
}
function handleFinish(options: { file: UploadFileInfo; event?: ProgressEvent }) {
const { file, event } = options;
// @ts-expect-error Ignore type errors
const responseText = event?.target?.responseText;
const response = JSON.parse(responseText);
const oss: Api.System.Oss = response.data;
file.id = String(oss.ossId);
file.url = oss.url;
file.name = oss.fileName;
window.$message?.success('上传成功');
return file;
}
function handleError(options: { file: UploadFileInfo; event?: ProgressEvent }) {
const { event } = options;
// @ts-expect-error Ignore type errors
const responseText = event?.target?.responseText;
const msg = JSON.parse(responseText).msg;
window.$message?.error(msg || '上传失败');
}
async function handleRemove(file: UploadFileInfo) {
if (file.status !== 'finished') {
return;
}
const { error } = await fetchBatchDeleteOss([file.id]);
if (error) return;
window.$message?.success('删除成功');
}
</script>
<template>
<NUpload
v-bind="attrs"
:action="`${baseURL}${action}`"
:headers="headers"
:max="max"
:accept="accept"
multiple
directory-dnd
:list-type="uploadType === 'image' ? 'image-card' : 'text'"
:is-error-state="isErrorState"
@finish="handleFinish"
@error="handleError"
@before-upload="beforeUpload"
@remove="({ file }) => handleRemove(file)"
>
<NUploadDragger v-if="uploadType === 'file'">
<div class="mb-12px flex-center">
<SvgIcon icon="material-symbols:unarchive-outline" class="text-58px color-#d8d8db dark:color-#a1a1a2" />
</div>
<NText class="text-16px">点击或者拖动文件到该区域来上传</NText>
<NP v-if="showTip" depth="3" class="mt-8px text-center">
请上传
<template v-if="max">
大小不超过
<b class="text-red-500">{{ max }}MB</b>
</template>
<template v-if="accept">
格式为
<b class="text-red-500">{{ accept.replaceAll(',', '/') }}</b>
</template>
的文件
</NP>
</NUploadDragger>
</NUpload>
<NP v-if="showTip && uploadType === 'image'" depth="3" class="mt-12px">
请上传
<template v-if="max">
大小不超过
<b class="text-red-500">{{ max }}MB</b>
</template>
<template v-if="accept">
格式为
<b class="text-red-500">{{ accept.replaceAll(',', '/') }}</b>
</template>
的文件
</NP>
</template>
<style scoped></style>

View File

@ -25,6 +25,7 @@ const local: App.I18n.Schema = {
deleteSuccess: 'Delete Success',
confirmDelete: 'Are you sure you want to delete?',
edit: 'Edit',
download: 'Download',
warning: 'Warning',
error: 'Error',
index: 'Index',
@ -182,7 +183,8 @@ const local: App.I18n.Schema = {
'monitor_oper-log': 'Operate Log',
system_client: 'Client Management',
system_notice: 'Notice Management',
'social-callback': 'Social Callback'
'social-callback': 'Social Callback',
system_oss: 'File Management'
},
page: {
login: {

View File

@ -25,6 +25,7 @@ const local: App.I18n.Schema = {
deleteSuccess: '删除成功',
confirmDelete: '确认删除吗?',
edit: '编辑',
download: '下载',
warning: '警告',
error: '错误',
index: '序号',
@ -182,7 +183,8 @@ const local: App.I18n.Schema = {
'monitor_oper-log': '操作日志',
system_client: '客户端管理',
system_notice: '通知公告',
'social-callback': '单点登录回调'
'social-callback': '单点登录回调',
system_oss: '文件管理'
},
page: {
login: {

View File

@ -35,6 +35,15 @@ export function fetchUpdateConfig(data: Api.System.ConfigOperateParams) {
});
}
/** 根据Key修改值 */
export function fetchUpdateConfigByKey(data: Api.System.ConfigOperateParams) {
return request<boolean>({
url: '/system/config/updateByKey',
method: 'put',
data
});
}
/** 批量删除参数配置 */
export function fetchBatchDeleteConfig(configIds: CommonType.IdType[]) {
return request<boolean>({

View File

@ -623,13 +623,15 @@ declare namespace Api {
fileName: string;
/** 原名 */
originalName: string;
/** 后缀名 */
/** 文件后缀名 */
fileSuffix: string;
/** 文件预览 */
/** URL地址 */
url: string;
/** 扩展属性 */
ext1: string;
/** 服务商 */
service: string;
/** 创建者 */
/** 创建者名称 */
createByName: string;
}>;
@ -637,6 +639,7 @@ declare namespace Api {
type OssSearchParams = CommonType.RecordNullable<
Pick<Api.System.Oss, 'fileName' | 'originalName' | 'fileSuffix' | 'service'> & Api.Common.CommonSearchParams
>;
/** oss list */
type OssList = Api.Common.PaginatingQueryRecord<Oss>;
}

View File

@ -319,6 +319,7 @@ declare namespace App {
deleteSuccess: string;
confirmDelete: string;
edit: string;
download: string;
warning: string;
error: string;
index: string;

View File

@ -22,6 +22,7 @@ declare module 'vue' {
DictSelect: typeof import('./../components/custom/dict-select.vue')['default']
DictTag: typeof import('./../components/custom/dict-tag.vue')['default']
ExceptionBase: typeof import('./../components/common/exception-base.vue')['default']
FileUpload: typeof import('./../components/custom/file-upload.vue')['default']
FormTip: typeof import('./../components/custom/form-tip.vue')['default']
FullScreen: typeof import('./../components/common/full-screen.vue')['default']
IconAntDesignEnterOutlined: typeof import('~icons/ant-design/enter-outlined')['default']
@ -30,10 +31,13 @@ declare module 'vue' {
IconEpCopyDocument: typeof import('~icons/ep/copy-document')['default']
IconGridiconsFullscreen: typeof import('~icons/gridicons/fullscreen')['default']
IconGridiconsFullscreenExit: typeof import('~icons/gridicons/fullscreen-exit')['default']
'IconHugeicons:configuration01': typeof import('~icons/hugeicons/configuration01')['default']
'IconIc:roundPlus': typeof import('~icons/ic/round-plus')['default']
IconIcRoundDelete: typeof import('~icons/ic/round-delete')['default']
IconIcRoundDownload: typeof import('~icons/ic/round-download')['default']
IconIcRoundEdit: typeof import('~icons/ic/round-edit')['default']
IconIcRoundFileUpload: typeof import('~icons/ic/round-file-upload')['default']
IconIcRoundImage: typeof import('~icons/ic/round-image')['default']
IconIcRoundPlus: typeof import('~icons/ic/round-plus')['default']
IconIcRoundRefresh: typeof import('~icons/ic/round-refresh')['default']
IconIcRoundRemove: typeof import('~icons/ic/round-remove')['default']
@ -87,6 +91,7 @@ declare module 'vue' {
NGi: typeof import('naive-ui')['NGi']
NGrid: typeof import('naive-ui')['NGrid']
NGridItem: typeof import('naive-ui')['NGridItem']
NImage: typeof import('naive-ui')['NImage']
NInput: typeof import('naive-ui')['NInput']
NInputGroup: typeof import('naive-ui')['NInputGroup']
NInputGroupLabel: typeof import('naive-ui')['NInputGroupLabel']
@ -101,6 +106,7 @@ declare module 'vue' {
NMessageProvider: typeof import('naive-ui')['NMessageProvider']
NModal: typeof import('naive-ui')['NModal']
NNotificationProvider: typeof import('naive-ui')['NNotificationProvider']
NP: typeof import('naive-ui')['NP']
NPopconfirm: typeof import('naive-ui')['NPopconfirm']
NPopover: typeof import('naive-ui')['NPopover']
NRadio: typeof import('naive-ui')['NRadio']
@ -119,10 +125,13 @@ declare module 'vue' {
NTabPane: typeof import('naive-ui')['NTabPane']
NTabs: typeof import('naive-ui')['NTabs']
NTag: typeof import('naive-ui')['NTag']
NText: typeof import('naive-ui')['NText']
NThing: typeof import('naive-ui')['NThing']
NTooltip: typeof import('naive-ui')['NTooltip']
NTree: typeof import('naive-ui')['NTree']
NTreeSelect: typeof import('naive-ui')['NTreeSelect']
NUpload: typeof import('naive-ui')['NUpload']
NUploadDragger: typeof import('naive-ui')['NUploadDragger']
NWatermark: typeof import('naive-ui')['NWatermark']
PinToggler: typeof import('./../components/common/pin-toggler.vue')['default']
PostSelect: typeof import('./../components/custom/post-select.vue')['default']

View File

@ -1,46 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue';
import { useAppStore } from '@/store/modules/app';
import HeaderBanner from './modules/header-banner.vue';
import CardData from './modules/card-data.vue';
import LineChart from './modules/line-chart.vue';
import PieChart from './modules/pie-chart.vue';
import ProjectNews from './modules/project-news.vue';
import CreativityBanner from './modules/creativity-banner.vue';
const appStore = useAppStore();
const gap = computed(() => (appStore.isMobile ? 0 : 16));
</script>
<script setup lang="ts"></script>
<template>
<NSpace vertical :size="16">
<NAlert :title="$t('common.warning')" type="warning">
{{ $t('page.home.branchDesc') }}
</NAlert>
<HeaderBanner />
<CardData />
<NGrid :x-gap="gap" :y-gap="16" responsive="screen" item-responsive>
<NGi span="24 s:24 m:14">
<NCard :bordered="false" class="card-wrapper">
<LineChart />
</NCard>
</NGi>
<NGi span="24 s:24 m:10">
<NCard :bordered="false" class="card-wrapper">
<PieChart />
</NCard>
</NGi>
</NGrid>
<NGrid :x-gap="gap" :y-gap="16" responsive="screen" item-responsive>
<NGi span="24 s:24 m:14">
<ProjectNews />
</NGi>
<NGi span="24 s:24 m:10">
<CreativityBanner />
</NGi>
</NGrid>
</NSpace>
<FileUpload />
</template>
<style scoped></style>

View File

@ -1,25 +1,30 @@
<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NImage, NPopconfirm } from 'naive-ui';
import { onMounted, ref } from 'vue';
import { NImage, NTag } from 'naive-ui';
import { useBoolean, useLoading } from '@sa/hooks';
import { fetchBatchDeleteOss, fetchGetOssList } from '@/service/api/system/oss';
import { fetchGetConfigByKey } from '@/service/api/system/config';
import { fetchGetConfigByKey, fetchUpdateConfigByKey } from '@/service/api/system/config';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAuth } from '@/hooks/business/auth';
import { useDownload } from '@/hooks/business/download';
import { isImage } from '@/utils/common';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import OssSearch from './modules/oss-search.vue';
import type { TableDataWithIndex } from '~/packages/hooks/src';
import OssUploadModal from './modules/oss-upload-modal.vue';
defineOptions({
name: 'OssList'
});
const appStore = useAppStore();
const { hasAuth } = useAuth();
const { oss } = useDownload();
const preview = ref(false);
const appStore = useAppStore();
const fileUploadType = ref<'file' | 'image'>('file');
const { bool: preview, setBool: setPreview } = useBoolean(true);
const { loading: previewLoading, startLoading: startPreviewLoading, endLoading: endPreviewLoading } = useLoading(false);
const { bool: uploadVisible, setTrue: showFUploadModal } = useBoolean(false);
const {
columns,
@ -55,37 +60,34 @@ const {
align: 'center',
width: 64
},
{
key: 'ossId',
title: '对象存储主键',
align: 'center',
minWidth: 120
},
{
key: 'fileName',
title: '文件名',
align: 'center',
ellipsis: {
tooltip: true
},
minWidth: 120
},
{
key: 'originalName',
title: '原名',
align: 'center',
ellipsis: {
tooltip: true
},
minWidth: 120
},
{
key: 'fileSuffix',
title: '后缀名',
title: '文件后缀名',
align: 'center',
minWidth: 120
},
{
key: 'url',
title: '文件预览',
title: 'URL地址',
align: 'center',
ellipsis: {
tooltip: true
},
minWidth: 120,
render: row => {
if (preview.value && isImage(row.fileSuffix)) {
@ -110,7 +112,10 @@ const {
key: 'service',
title: '服务商',
align: 'center',
minWidth: 120
minWidth: 120,
render: row => {
return <NTag type="primary">{row.service}</NTag>;
}
},
{
key: 'operate',
@ -119,33 +124,40 @@ const {
width: 130,
render: row => {
const downloadBtn = () => {
if (!hasAuth('system:oss:download')) {
return null;
}
return (
<NButton type="primary" ghost size="small" onClick={() => handleDownload(row)}>
下载
</NButton>
<ButtonIcon
text
type="primary"
icon="material-symbols:download"
class="text-20px"
tooltipContent={$t('common.download')}
onClick={() => download(row.ossId!)}
/>
);
};
const deleteBtn = () => {
if (!hasAuth('system:oss:remove')) {
if (!hasAuth('system:oss:delete')) {
return null;
}
return (
<NPopconfirm onPositiveClick={() => handleDelete(row.ossId!)}>
{{
default: () => $t('common.confirmDelete'),
trigger: () => (
<NButton type="error" ghost size="small">
{$t('common.delete')}
</NButton>
)
}}
</NPopconfirm>
<ButtonIcon
text
type="error"
icon="material-symbols:delete-outline"
class="text-20px"
tooltipContent={$t('common.delete')}
popconfirmContent={$t('common.confirmDelete')}
onPositiveClick={() => handleDelete(row.ossId!)}
/>
);
};
return (
<div class="flex-center gap-8px">
<div class="flex-center gap-16px">
{downloadBtn()}
{deleteBtn()}
</div>
@ -155,7 +167,7 @@ const {
]
});
const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);
const { handleAdd, checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);
async function handleBatchDelete() {
// request
@ -171,38 +183,104 @@ async function handleDelete(ossId: CommonType.IdType) {
onDeleted();
}
function download(ossId: CommonType.IdType) {
oss(ossId);
}
function handleUpload(type: 'file' | 'image') {
fileUploadType.value = type;
showFUploadModal();
}
async function getConfigKey() {
const { data: previewStr, error } = await fetchGetConfigByKey('sys.oss.previewListResource');
if (error) return;
preview.value = previewStr === 'true';
setPreview(previewStr === 'true');
}
getConfigKey();
function handleDownload(row: TableDataWithIndex<Api.System.Oss>) {
oss(row.ossId);
onMounted(() => {
getConfigKey();
});
async function handleUpdatePreview(checked: boolean) {
setPreview(!checked);
window.$dialog?.warning({
title: '提示',
content: `是否确认${checked ? '开启' : '关闭'}预览?`,
positiveText: '确认',
negativeText: '取消',
onPositiveClick: async () => {
startPreviewLoading();
const { error } = await fetchUpdateConfigByKey({
configKey: 'sys.oss.previewListResource',
configValue: String(checked)
});
if (error) {
setPreview(!checked);
endPreviewLoading();
return;
}
setPreview(checked);
window.$message?.success('更新成功');
endPreviewLoading();
},
onNegativeClick: () => {
setPreview(!checked);
}
});
}
</script>
<template>
<div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
<OssSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
<NCard title="文件管理列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
<NCard title="OSS 对象存储列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
<template #header-extra>
<TableHeaderOperation
v-model:columns="columnChecks"
:disabled-delete="checkedRowKeys.length === 0"
:loading="loading"
:show-add="false"
:show-delete="hasAuth('system:oss:remove')"
:show-export="false"
:show-delete="hasAuth('system:oss:delete')"
@add="handleAdd"
@delete="handleBatchDelete"
@refresh="getData"
>
<template #prefix>
<NSwitch v-model:value="preview">
<template #checked>开启预览</template>
<template #unchecked>关闭预览</template>
<NSwitch
v-model:value="preview"
class="mt-1px"
:loading="previewLoading"
size="large"
:round="false"
@update:value="handleUpdatePreview"
>
<template #checked>
<span class="text-14px">禁用预览</span>
</template>
<template #unchecked>
<span class="text-14px">开启预览</span>
</template>
</NSwitch>
<NButton type="primary" size="small" ghost @click="handleUpload('file')">
<template #icon>
<icon-ic-round-file-upload />
</template>
上传文件
</NButton>
<NButton type="primary" size="small" ghost @click="handleUpload('image')">
<template #icon>
<icon-ic-round-image />
</template>
上传图片
</NButton>
<NButton type="primary" size="small" ghost>
<template #icon>
<icon-hugeicons:configuration-01 />
</template>
配置管理
</NButton>
</template>
</TableHeaderOperation>
</template>
@ -217,11 +295,15 @@ function handleDownload(row: TableDataWithIndex<Api.System.Oss>) {
remote
:row-key="row => row.ossId"
:pagination="mobilePagination"
:row-props="() => ({ class: 'w-70px h-70px' })"
class="sm:h-full"
/>
<OssUploadModal v-model:visible="uploadVisible" :upload-type="fileUploadType" @close="getData" />
</NCard>
</div>
</template>
<style scoped></style>
<style scoped>
.n-switch {
--n-rail-height: 27px !important;
}
</style>

View File

@ -1,6 +1,7 @@
<script setup lang="ts">
import { $t } from '@/locales';
import { ref } from 'vue';
import { useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
defineOptions({
name: 'OssSearch'
@ -15,15 +16,22 @@ const emit = defineEmits<Emits>();
const { formRef, validate, restoreValidation } = useNaiveForm();
const dateRangeCreateTime = ref<[string, string]>();
const model = defineModel<Api.System.OssSearchParams>('model', { required: true });
async function reset() {
dateRangeCreateTime.value = undefined;
await restoreValidation();
emit('reset');
}
async function search() {
await validate();
if (dateRangeCreateTime.value?.length) {
model.value.params!.beginCreateTime = dateRangeCreateTime.value[0];
model.value.params!.endCreateTime = dateRangeCreateTime.value[0];
}
emit('search');
}
</script>
@ -32,7 +40,7 @@ async function search() {
<NCard :bordered="false" size="small" class="card-wrapper">
<NCollapse>
<NCollapseItem :title="$t('common.search')" name="user-search">
<NForm ref="formRef" :model="model" label-placement="left" :label-width="80">
<NForm ref="formRef" :model="model" label-placement="left" :label-width="100">
<NGrid responsive="screen" item-responsive>
<NFormItemGi span="24 s:12 m:6" label="文件名" path="fileName" class="pr-24px">
<NInput v-model:value="model.fileName" placeholder="请输入文件名" />
@ -40,13 +48,21 @@ async function search() {
<NFormItemGi span="24 s:12 m:6" label="原名" path="originalName" class="pr-24px">
<NInput v-model:value="model.originalName" placeholder="请输入原名" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="后缀名" path="fileSuffix" class="pr-24px">
<NInput v-model:value="model.fileSuffix" placeholder="请输入后缀名" />
<NFormItemGi span="24 s:12 m:6" label="文件后缀名" path="fileSuffix" class="pr-24px">
<NInput v-model:value="model.fileSuffix" placeholder="请输入文件后缀名" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="服务商" path="service" class="pr-24px">
<NInput v-model:value="model.service" placeholder="请输入服务商" />
</NFormItemGi>
<NFormItemGi span="24" class="pr-24px">
<NFormItemGi span="24 s:12 m:12" label="创建时间" path="createTime" class="pr-24px">
<NDatePicker
v-model:formatted-value="dateRangeCreateTime"
type="datetimerange"
value-format="yyyy-MM-dd HH:mm:ss"
clearable
/>
</NFormItemGi>
<NFormItemGi span="24 s:12 m:12" class="pr-24px">
<NSpace class="w-full" justify="end">
<NButton @click="reset">
<template #icon>

View File

@ -0,0 +1,60 @@
<script setup lang="ts">
import { computed, watch } from 'vue';
defineOptions({
name: 'OssUploadModal'
});
interface Props {
uploadType: 'file' | 'image';
}
const props = defineProps<Props>();
interface Emits {
(e: 'close'): void;
}
const emit = defineEmits<Emits>();
const visible = defineModel<boolean>('visible', {
default: false
});
const accept = computed(() => {
return props.uploadType === 'file' ? '.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.pdf' : '.jpg,.jpeg,.png,.gif,.bmp,.webp';
});
function handleUpdateModelWhenUpload() {}
function closeDrawer() {
visible.value = false;
}
function handleClose() {
closeDrawer();
emit('close');
}
watch(visible, () => {
if (visible.value) {
handleUpdateModelWhenUpload();
}
});
</script>
<template>
<NModal
v-model:show="visible"
class="max-h-520px max-w-90% w-600px"
preset="card"
:title="`上传${uploadType === 'file' ? '文件' : '图片'}`"
size="huge"
:bordered="false"
@after-leave="handleClose"
>
<FileUpload :upload-type="uploadType" :accept="accept" />
</NModal>
</template>
<style scoped></style>

View File

@ -117,6 +117,7 @@ const {
text
type="primary"
icon="material-symbols:drive-file-rename-outline-outline"
class="text-18px"
tooltipContent={$t('common.edit')}
onClick={() => edit(row.userId!)}
/>
@ -132,6 +133,7 @@ const {
text
type="error"
icon="material-symbols:delete-outline"
class="text-18px"
tooltipContent={$t('common.delete')}
popconfirmContent={$t('common.confirmDelete')}
onPositiveClick={() => handleDelete(row.userId!)}