feat(cms): 图片库升级为素材库,支持文档与音视频,缩略图统一 4:3

/cms/photo 原来只能传图片(accept=image/*,前后端各拦一次),甲方要求支持常见
文档格式与音视频,并统一缩略图宽高。

- index:标题改「素材库」,上传放开全类型,新增类型筛选(全部/图片/文档/音频/视频)
- image / list:封面统一 4:3(网格 aspect-ratio + object-fit: cover,列表 120x90);
  图片改用 thumbnail 地址(原来直接拉原图);文档/音频用类型图标卡,视频用图标卡
  加播放角标;点击视频/音频开 MediaPreview 弹窗,文档新窗口打开
- photo-edit:去掉上传表单(上传即入库,弹窗只改元数据),顺带修掉「上传已由后端
  落一条记录、点保存又 addFiles 插一条无 path 空记录」的重复入库 bug;分享代码按
  类型分流(图片 img 系列 / 视频 video / 音频 audio / 文档只给链接与下载)
- utils/media.ts:媒体大类判定、上传校验、大小格式化、类型图标与配色的唯一出口,
  MEDIA_ACCEPT 是后端 UploadRules 的镜像,两边要一起改
This commit is contained in:
2026-11-01 21:03:56 +08:00
parent 6d19cb5a05
commit 42fddc5c85
7 changed files with 729 additions and 199 deletions
+2
View File
@@ -39,6 +39,8 @@ export interface FileRecordParam extends PageParam {
name?: string;
path?: string;
contentType?: string;
// 媒体大类: image/video/audio/doc,空表示不限
mediaCategory?: string;
createNickname?: string;
count?: number;
page?: number;
+220
View File
@@ -0,0 +1,220 @@
import type { Component } from 'vue';
import {
CustomerServiceOutlined,
FileExcelOutlined,
FileMarkdownOutlined,
FilePdfOutlined,
FilePptOutlined,
FileTextOutlined,
FileUnknownOutlined,
FileWordOutlined,
VideoCameraOutlined
} from '@ant-design/icons-vue';
import type { FileRecord } from '@/api/system/file/model';
/**
* 媒体大类。
*
* 注意它和 `contentType`(MIME 字符串)不是一回事:MIME 里「文档」没有统一前缀
* (pdf/docx/zip 都是 application/…),所以大类由 MIME 前缀 + 后缀一起判定。
*/
export type MediaKind = 'image' | 'video' | 'audio' | 'doc';
/** 与后端 UploadRules 的白名单保持一致,改这里要同步改后端 */
export const MEDIA_ACCEPT = [
'image/*',
'.pdf',
'.doc',
'.docx',
'.xls',
'.xlsx',
'.ppt',
'.pptx',
'.txt',
'.md',
'.csv',
'.mp3',
'.wav',
'.m4a',
'.aac',
'.mp4',
'.mov',
'.webm'
].join(',');
const DOC_SUFFIXES = [
'pdf',
'doc',
'docx',
'xls',
'xlsx',
'ppt',
'pptx',
'txt',
'md',
'csv'
];
const VIDEO_SUFFIXES = ['mp4', 'mov', 'webm'];
const AUDIO_SUFFIXES = ['mp3', 'wav', 'm4a', 'aac'];
/** 图片大小上限(MB),其余类型上限(MB),受后端 multipart 100MB 硬顶约束 */
export const MEDIA_MAX_MB_IMAGE = 10;
export const MEDIA_MAX_MB_OTHER = 100;
/** 类型筛选项,value 为空表示不限 */
export const MEDIA_CATEGORY_OPTIONS: { value: string; label: string }[] = [
{ value: '', label: '全部类型' },
{ value: 'image', label: '图片' },
{ value: 'doc', label: '文档' },
{ value: 'audio', label: '音频' },
{ value: 'video', label: '视频' }
];
export const MEDIA_KIND_LABEL: Record<MediaKind, string> = {
image: '图片',
video: '视频',
audio: '音频',
doc: '文档'
};
/** 取小写后缀,不带点 */
export function mediaSuffix(name?: string | null): string {
if (!name || name.lastIndexOf('.') < 0) {
return '';
}
return name.substring(name.lastIndexOf('.') + 1).toLowerCase();
}
/** 由 MIME + 文件名判定大类 */
export function mediaKindOf(
contentType?: string | null,
name?: string | null
): MediaKind {
const mime = (contentType || '').toLowerCase();
if (mime.startsWith('image/')) {
return 'image';
}
if (mime.startsWith('video/')) {
return 'video';
}
if (mime.startsWith('audio/')) {
return 'audio';
}
const suffix = mediaSuffix(name);
if (VIDEO_SUFFIXES.includes(suffix)) {
return 'video';
}
if (AUDIO_SUFFIXES.includes(suffix)) {
return 'audio';
}
return 'doc';
}
/** 由文件记录判定大类 */
export function mediaKindOfRecord(record?: FileRecord | null): MediaKind {
return mediaKindOf(record?.contentType, record?.path || record?.name);
}
/**
* 上传前校验,通过返回 null,不通过返回给用户看的错误文案。
* 与后端同规则:图片按 MIME 认,其余按后缀白名单认。
*/
export function validateMediaFile(file: File): string | null {
const mime = (file.type || '').toLowerCase();
const suffix = mediaSuffix(file.name);
const isImage = mime.startsWith('image/');
if (!isImage) {
const allowed =
DOC_SUFFIXES.includes(suffix) ||
VIDEO_SUFFIXES.includes(suffix) ||
AUDIO_SUFFIXES.includes(suffix);
if (!allowed) {
return '不支持的文件格式,仅支持图片、文档、音频、视频';
}
}
const maxMb = isImage ? MEDIA_MAX_MB_IMAGE : MEDIA_MAX_MB_OTHER;
if (file.size / 1024 / 1024 > maxMb) {
return `文件大小不能超过 ${maxMb}MB`;
}
return null;
}
/** 文件大小格式化 */
export function formatFileSize(length?: number | null): string {
const size = Number(length ?? 0);
if (!size || size < 0) {
return '-';
}
if (size < 1024) {
return size + 'B';
}
if (size < 1024 * 1024) {
return (size / 1024).toFixed(1) + 'KB';
}
if (size < 1024 * 1024 * 1024) {
return (size / 1024 / 1024).toFixed(1) + 'M';
}
return (size / 1024 / 1024 / 1024).toFixed(1) + 'G';
}
/** 卡片/表格里显示的类型图标 */
export function mediaIcon(kind: MediaKind, name?: string | null): Component {
if (kind === 'audio') {
return CustomerServiceOutlined;
}
if (kind === 'video') {
return VideoCameraOutlined;
}
switch (mediaSuffix(name)) {
case 'pdf':
return FilePdfOutlined;
case 'doc':
case 'docx':
return FileWordOutlined;
case 'xls':
case 'xlsx':
case 'csv':
return FileExcelOutlined;
case 'ppt':
case 'pptx':
return FilePptOutlined;
case 'md':
return FileMarkdownOutlined;
case 'txt':
return FileTextOutlined;
default:
return FileUnknownOutlined;
}
}
/** 图标色,按类型区分但都压在中低饱和,避免卡片花花绿绿 */
export function mediaColor(kind: MediaKind, name?: string | null): string {
if (kind === 'audio') {
return '#805ad5';
}
if (kind === 'video') {
return '#2b6cb0';
}
switch (mediaSuffix(name)) {
case 'pdf':
return '#e5484d';
case 'doc':
case 'docx':
return '#2b6cb0';
case 'xls':
case 'xlsx':
case 'csv':
return '#2f855a';
case 'ppt':
case 'pptx':
return '#c05621';
default:
return '#718096';
}
}
/** 非图片卡片右下角的扩展名徽标文本 */
export function mediaExtLabel(record?: FileRecord | null): string {
const suffix = mediaSuffix(record?.path || record?.name);
return suffix ? suffix.toUpperCase() : 'FILE';
}
@@ -0,0 +1,93 @@
<!-- 音频 / 视频预览弹窗:素材库里非图片项的统一播放器 -->
<template>
<ele-modal
:width="kind === 'video' ? 880 : 480"
:footer="null"
:visible="visible"
:title="record?.name"
:destroy-on-close="true"
@update:visible="updateVisible"
>
<div v-if="visible && record" class="media-preview">
<ele-xg-player
v-if="kind === 'video'"
:key="'v-' + record.id"
:config="playerConfig"
/>
<div v-else class="media-preview-audio">
<customer-service-outlined class="media-preview-audio-icon" />
<div class="media-preview-audio-name ele-text-secondary">
{{ record.name }}
</div>
<audio
:key="'a-' + record.id"
:src="record.url"
controls
autoplay
class="media-preview-audio-player"
></audio>
</div>
</div>
</ele-modal>
</template>
<script lang="ts" setup>
import { computed } from 'vue';
import { CustomerServiceOutlined } from '@ant-design/icons-vue';
import type { FileRecord } from '@/api/system/file/model';
import { mediaKindOfRecord } from '@/utils/media';
const props = defineProps<{
// 弹窗是否打开
visible: boolean;
// 当前预览的文件
record?: FileRecord | null;
}>();
const emit = defineEmits<{
(e: 'update:visible', visible: boolean): void;
}>();
const kind = computed(() => mediaKindOfRecord(props.record));
// xgplayer 配置,key 变化时重建实例,避免沿用上一条的播放状态
const playerConfig = computed(() => ({
id: 'cmsPhotoPreviewPlayer',
lang: 'zh-cn',
fluid: true,
url: props.record?.url,
playbackRate: [0.5, 1, 1.5, 2],
pip: true
}));
/* 更新 visible */
const updateVisible = (value: boolean) => {
emit('update:visible', value);
};
</script>
<style lang="less" scoped>
.media-preview-audio {
display: flex;
flex-direction: column;
align-items: center;
padding: 16px 0 8px;
}
.media-preview-audio-icon {
font-size: 48px;
color: #805ad5;
}
.media-preview-audio-name {
margin: 12px 0 20px;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.media-preview-audio-player {
width: 100%;
}
</style>
+113 -113
View File
@@ -1,10 +1,10 @@
<!-- 角色编辑弹窗 -->
<!-- 素材编辑弹窗:文件在列表页上传时已入库,这里只改元数据和分享代码 -->
<template>
<ele-modal
:width="600"
:visible="visible"
:confirm-loading="loading"
:title="isUpdate ? '编辑' : '上传文件'"
title="编辑素材"
:body-style="{ paddingBottom: '8px' }"
okText="保存"
@update:visible="updateVisible"
@@ -19,27 +19,22 @@
styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
"
>
<a-form-item label="上传文件" name="fileName" v-if="!isUpdate">
<span
class="ele-text-success"
v-if="fileName"
style="margin-right: 10px"
>
{{ fileName }}
</span>
<a-upload
:show-upload-list="false"
:accept="'video/*'"
v-if="!fileName"
:customRequest="onUpload"
>
<a-button type="primary" class="ele-btn-icon">
<template #icon>
<UploadOutlined />
</template>
<span>上传文件</span>
</a-button>
</a-upload>
<a-form-item label="文件">
<div class="media-file">
<component
:is="fileIcon"
class="media-file-icon"
:style="{ color: fileColor }"
/>
<div class="media-file-info">
<div class="media-file-name" :title="record?.name">
{{ record?.name }}
</div>
<div class="ele-text-secondary media-file-sub">
{{ kindLabel }} · {{ fileSize }}
</div>
</div>
</div>
</a-form-item>
<a-form-item label="文件名称" name="name">
<a-input
@@ -53,17 +48,17 @@
<a-textarea
:rows="4"
:maxlength="200"
placeholder="图片描述"
placeholder="素材描述"
v-model:value="form.comments"
/>
</a-form-item>
<div style="margin-bottom: 22px">
<a-divider orientation="left">图片分享</a-divider>
<a-divider orientation="left">{{ shareTitle }}</a-divider>
</div>
<a-form-item label="图片URL链接">
<a-form-item label="素材链接">
<a-input v-model:value="share.url" @click="copyText(share.url)" />
</a-form-item>
<a-form-item label="网页代码(HTML)">
<a-form-item label="网页代码(HTML)" v-if="share.html">
<a-input v-model:value="share.html" @click="copyText(share.html)" />
</a-form-item>
<a-form-item label="Markdown">
@@ -72,38 +67,36 @@
@click="copyText(share.Markdown)"
/>
</a-form-item>
<a-form-item label="论坛BBCode">
<a-form-item label="论坛BBCode" v-if="share.bbCode">
<a-input v-model:value="share.bbCode" @click="copyText(share.bbCode)" />
</a-form-item>
<!-- <a-form-item label="封面图" name="images">-->
<!-- <ele-image-upload-->
<!-- v-model:value="images"-->
<!-- :limit="1"-->
<!-- :drag="true"-->
<!-- :item-style="{ width: '60px', height: '60px' }"-->
<!-- :accept="'image/*'"-->
<!-- :upload-handler="uploadHandler"-->
<!-- @upload="onUpload"-->
<!-- />-->
<!-- </a-form-item>-->
<a-form-item label="下载地址">
<a-input
v-model:value="share.download"
@click="copyText(share.download)"
/>
</a-form-item>
</a-form>
</ele-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { computed, reactive, ref, watch } from 'vue';
import { message } from 'ant-design-vue/es';
import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import { storeToRefs } from 'pinia';
import { useThemeStore } from '@/store/modules/theme';
import useFormData from '@/utils/use-form-data';
import type { FileRecord } from '@/api/system/file/model';
import { messageLoading } from 'ele-admin-pro';
import { addFiles, updateFiles, uploadFile } from '@/api/system/file';
import { UploadOutlined } from '@ant-design/icons-vue';
import { RuleObject } from 'ant-design-vue/es/form';
import { updateFiles } from '@/api/system/file';
import { copyText } from '@/utils/common';
import {
formatFileSize,
mediaColor,
mediaIcon,
mediaKindOfRecord,
MEDIA_KIND_LABEL
} from '@/utils/media';
// 是否开启响应式布局
const themeStore = useThemeStore();
@@ -121,20 +114,11 @@
data?: FileRecord | null;
}>();
//
const formRef = ref<FormInstance | null>(null);
const fileName = ref('');
// 是否是修改
const isUpdate = ref(false);
// 当前编辑的原始记录,分享代码依赖它的 url,不随表单变化
const record = ref<FileRecord | null>(null);
// 提交状态
const loading = ref(false);
// 图片资源分享
const share = ref({
url: '',
Markdown: '',
html: '',
bbCode: ''
});
// 表单数据
const { form, resetFields, assignFields } = useFormData<FileRecord>({
@@ -143,22 +127,49 @@
comments: ''
});
const kind = computed(() => mediaKindOfRecord(record.value));
const kindLabel = computed(() => MEDIA_KIND_LABEL[kind.value]);
const fileSize = computed(() => formatFileSize(record.value?.length));
const fileIcon = computed(() =>
mediaIcon(kind.value, record.value?.path || record.value?.name)
);
const fileColor = computed(() =>
mediaColor(kind.value, record.value?.path || record.value?.name)
);
// 文档给的是链接与下载地址,图片/音视频给的是嵌入代码
const shareTitle = computed(() =>
kind.value === 'doc' ? '素材链接' : '素材分享'
);
/**
* 分享代码按类型生成:图片沿用 img 系列,音视频给 video/audio 标签,
* 文档只给直链和下载地址(不提供 HTML 嵌入)。
*/
const share = computed(() => {
const data = record.value;
const url = data?.url || '';
const name = data?.name || '';
const result = {
url,
html: '',
Markdown: `[${name}](${url})`,
bbCode: `[url=${url}]${name}[/url]`,
download: data?.downloadUrl || ''
};
if (kind.value === 'image') {
result.html = `<a href="${url}"><img src="${url}" alt="${name}" border="0" /></a>`;
result.Markdown = `[![${name}](${url})](${url})`;
result.bbCode = `[url=${url}][img]${url}[/img][/url]`;
} else if (kind.value === 'video') {
result.html = `<video src="${url}" controls></video>`;
} else if (kind.value === 'audio') {
result.html = `<audio src="${url}" controls></audio>`;
}
return result;
});
// 表单验证规则
const rules = reactive<Record<string, Rule[]>>({
fileName: [
{
required: true,
message: '请上传文件',
type: 'string',
trigger: 'blur',
validator: async (_rule: RuleObject) => {
if (!isUpdate.value && fileName.value.length == 0) {
return Promise.reject('请上传文件');
}
return Promise.resolve();
}
}
],
name: [
{
required: true,
@@ -169,39 +180,6 @@
]
});
// 上传文件
const onUpload = (item) => {
const { file } = item;
if (!file.type.startsWith('video')) {
message.error('文件格式不正确!');
return;
}
if (file.size / 1024 / 1024 > 100) {
message.error('大小不能超过 100MB');
return;
}
const hide = messageLoading({
content: '上传中..',
duration: 0,
mask: true
});
uploadFile(file)
.then((data) => {
hide();
fileName.value = String(data.name);
// images.value.push({
// uid: data.id,
// url: FILE_THUMBNAIL + data.path,
// status: 'done'
// });
message.success('上传成功');
})
.catch((e) => {
message.error(e.message);
hide();
});
};
/* 保存编辑 */
const save = () => {
if (!formRef.value) {
@@ -211,8 +189,7 @@
.validate()
.then(() => {
loading.value = true;
const saveOrUpdate = isUpdate.value ? updateFiles : addFiles;
saveOrUpdate(form)
updateFiles(form)
.then((msg) => {
loading.value = false;
message.success(msg);
@@ -236,21 +213,44 @@
() => props.visible,
(visible) => {
if (visible) {
record.value = props.data ?? null;
if (props.data) {
assignFields(props.data);
// 图片分享代码
share.value.url = `${props.data.url}`;
share.value.html = `<a href="${props.data.url}"><img src="${props.data.url}" alt="${props.data.name}" border="0" /></a>`;
share.value.Markdown = `[![${props.data.name}](${props.data.url})](${props.data.url})`;
share.value.bbCode = `[url=${props.data.url}][img]${props.data.url}[/img][/url]`;
isUpdate.value = true;
} else {
isUpdate.value = false;
}
} else {
record.value = null;
resetFields();
formRef.value?.clearValidate();
}
}
);
</script>
<style lang="less" scoped>
.media-file {
display: flex;
align-items: center;
min-width: 0;
}
.media-file-icon {
flex: none;
font-size: 32px;
}
.media-file-info {
flex: 1;
min-width: 0;
margin-left: 10px;
}
.media-file-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.media-file-sub {
font-size: 12px;
}
</style>
+131 -28
View File
@@ -1,9 +1,10 @@
<!-- 素材库 · 网格视图 -->
<template>
<div class="page">
<a-row :gutter="20">
<a-col
v-for="(item, index) in data"
:key="index"
v-for="item in data"
:key="item.id"
v-bind="
styleResponsive
? { xl: 4, lg: 8, md: 12, sm: 12, xs: 24 }
@@ -12,10 +13,33 @@
>
<a-card :bordered="false" hoverable style="margin-top: 16px">
<template #cover>
<a-image :src="item.url" alt="" />
<!-- 统一 4:3 封面盒子:图片裁剪填充,其余类型放类型图标 -->
<div class="media-cover" @click="openPreview(item)">
<a-image
v-if="kindOf(item) === 'image'"
class="media-cover-image"
:src="item.thumbnail || item.url"
:preview="{ src: item.url }"
/>
<template v-else>
<component
:is="iconOf(item)"
class="media-cover-icon"
:style="{ color: colorOf(item) }"
/>
<span class="media-cover-ext">{{ extOf(item) }}</span>
<play-circle-filled
v-if="kindOf(item) === 'video'"
class="media-cover-play"
/>
</template>
</div>
</template>
<a-card-meta :title="item.name" @click="openEdit(item)">
<template #description>
<div class="media-meta">
{{ labelOf(item) }} · {{ sizeOf(item) }}
</div>
<div
class="project-list-desc"
v-if="item.comments"
@@ -41,58 +65,85 @@
</a-row>
<!-- 编辑弹窗 -->
<PhotoEdit v-model:visible="showEdit" :data="current" @done="query" />
<!-- 音视频预览 -->
<MediaPreview v-model:visible="showPreview" :record="current" />
</div>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { ref } from 'vue';
import { storeToRefs } from 'pinia';
import { PlayCircleFilled } from '@ant-design/icons-vue';
import { useThemeStore } from '@/store/modules/theme';
import { FileRecord, FileRecordParam } from '@/api/system/file/model';
import type { FileRecord, FileRecordParam } from '@/api/system/file/model';
import PhotoEdit from './components/photo-edit.vue';
import MediaPreview from './components/media-preview.vue';
import { timeAgo } from 'ele-admin-pro';
import {
formatFileSize,
mediaColor,
mediaExtLabel,
mediaIcon,
mediaKindOfRecord,
MEDIA_KIND_LABEL,
type MediaKind
} from '@/utils/media';
const props = defineProps<{
// 搜索关键字
searchText: string;
defineProps<{
// 列表数据
data?: FileRecord[];
// 搜索条件
where?: FileRecordParam | null;
// 修改回显的数据
data?: FileRecord | null;
}>();
// 当前编辑数据
const current = ref<FileRecord | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
const emit = defineEmits<{
(e: 'done'): void;
}>();
// 当前操作的数据(编辑 / 预览共用)
const current = ref<FileRecord | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
// 是否显示音视频预览
const showPreview = ref(false);
// 是否开启响应式布局
const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);
const kindOf = (item: FileRecord): MediaKind => mediaKindOfRecord(item);
const iconOf = (item: FileRecord) =>
mediaIcon(kindOf(item), item.path || item.name);
const colorOf = (item: FileRecord) =>
mediaColor(kindOf(item), item.path || item.name);
const extOf = (item: FileRecord) => mediaExtLabel(item);
const labelOf = (item: FileRecord) => MEDIA_KIND_LABEL[kindOf(item)];
const sizeOf = (item: FileRecord) => formatFileSize(item.length);
/* 打开编辑弹窗 */
const openEdit = (row?: FileRecord) => {
current.value = row ?? null;
showEdit.value = true;
};
// 是否开启响应式布局
const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);
/* 点击封面:图片由 a-image 自己预览,音视频开播放器,文档新窗口打开 */
const openPreview = (row: FileRecord) => {
const kind = kindOf(row);
if (kind === 'image') {
return;
}
if (kind === 'doc') {
window.open(row.url, '_blank');
return;
}
current.value = row;
showPreview.value = true;
};
/* 刷新列表 */
const query = () => {
emit('done');
};
watch(
() => props.data,
(visible) => {
if (visible) {
console.log(props.data);
} else {
}
}
);
</script>
<script lang="ts">
@@ -102,6 +153,58 @@
</script>
<style lang="less" scoped>
.media-cover {
position: relative;
display: flex;
align-items: center;
justify-content: center;
// 所有类型共用 4:3,混排时卡片高度才对得齐
aspect-ratio: 4 / 3;
overflow: hidden;
background: #f5f6f8;
cursor: pointer;
:deep(.ant-image) {
width: 100%;
height: 100%;
}
:deep(.ant-image-img) {
width: 100%;
height: 100%;
object-fit: cover;
}
}
.media-cover-icon {
font-size: 40px;
}
.media-cover-ext {
position: absolute;
right: 8px;
bottom: 8px;
padding: 0 6px;
font-size: 12px;
line-height: 18px;
color: #718096;
background: rgba(255, 255, 255, 0.9);
border-radius: 3px;
}
.media-cover-play {
position: absolute;
font-size: 44px;
color: rgba(255, 255, 255, 0.92);
filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.35));
}
.media-meta {
margin-bottom: 2px;
font-size: 12px;
color: #8c8c8c;
}
.project-list-desc {
height: 44px;
line-height: 22px;
+37 -27
View File
@@ -1,7 +1,7 @@
<template>
<div class="page">
<a-page-header :ghost="false" title="图片库">
<div class="ele-text-secondary"> 上传、分享有价值的图片素材 </div>
<a-page-header :ghost="false" title="素材库">
<div class="ele-text-secondary"> 上传、分享图片、文档与音视频素材 </div>
<template #footer>
<a-tabs v-model:activeKey="activeKey">
<a-tab-pane key="1" tab="网格模式" />
@@ -10,16 +10,29 @@
<div style="margin-bottom: 10px">
<a-upload
:show-upload-list="false"
:accept="'image/*'"
:accept="MEDIA_ACCEPT"
:customRequest="onUpload"
>
<a-button key="1" type="primary" class="ele-btn-icon">
<template #icon>
<UploadOutlined />
</template>
<span>上传图片</span>
<span>上传素材</span>
</a-button>
</a-upload>
<a-select
v-model:value="category"
style="width: 120px; margin-left: 10px"
@change="onCategoryChange"
>
<a-select-option
v-for="item in MEDIA_CATEGORY_OPTIONS"
:key="item.value"
:value="item.value"
>
{{ item.label }}
</a-select-option>
</a-select>
<a-input-search
allow-clear
style="width: 360px; margin-left: 10px"
@@ -68,15 +81,22 @@
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { FileRecord, FileRecordParam } from '@/api/system/file/model';
import type { FileRecord, FileRecordParam } from '@/api/system/file/model';
import Image from './image.vue';
import List from './list.vue';
import { messageLoading } from 'ele-admin-pro';
import { pageFiles, uploadFile } from '@/api/system/file';
import { message } from 'ant-design-vue/es';
import {
MEDIA_ACCEPT,
MEDIA_CATEGORY_OPTIONS,
validateMediaFile
} from '@/utils/media';
const type = ref('name');
const searchText = ref('');
// 媒体大类筛选,空串表示全部
const category = ref('');
const data = ref<FileRecord[]>([]);
// 当前选项卡
const activeKey = ref('1');
@@ -94,7 +114,6 @@
/* 查询数据 */
const query = () => {
console.log('query()');
if (type.value == 'name') {
where.name = searchText.value;
}
@@ -103,8 +122,8 @@
}
where.page = page.value;
where.limit = limit.value;
where.contentType = 'image';
console.log(where);
// 空串会被当成一个真实的筛选值,必须置空
where.mediaCategory = category.value || undefined;
const hide = messageLoading('请求中..', 0);
pageFiles(where).then((res) => {
count.value = Number(res?.count);
@@ -113,17 +132,20 @@
});
};
/* 切换类型回到第一页 */
const onCategoryChange = () => {
page.value = 1;
query();
};
query();
// 上传文件
const onUpload = (item) => {
const { file } = item;
if (!file.type.startsWith('image')) {
message.error('只能选择图片');
return;
}
if (file.size / 1024 / 1024 > 10) {
message.error('大小不能超过 10MB');
const error = validateMediaFile(file);
if (error) {
message.error(error);
return;
}
const hide = messageLoading({
@@ -132,7 +154,7 @@
mask: true
});
uploadFile(file)
.then((data) => {
.then(() => {
hide();
message.success('上传成功');
query();
@@ -149,15 +171,3 @@
name: 'PhotoIndex'
};
</script>
<style lang="less" scoped>
.project-list-desc {
height: 44px;
line-height: 22px;
margin-bottom: 20px;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>
+133 -31
View File
@@ -1,3 +1,4 @@
<!-- 素材库 · 列表视图 -->
<template>
<div class="page">
<a-card :bordered="false">
@@ -8,21 +9,21 @@
:columns="columns"
:datasource="datasource"
v-model:selection="selection"
:scroll="{ x: 800 }"
cache-key="proCmsVideoTable"
:scroll="{ x: 860 }"
cache-key="proCmsPhotoTable"
>
<template #toolbar>
<a-space>
<a-upload
:show-upload-list="false"
:accept="'image/*'"
:accept="MEDIA_ACCEPT"
:customRequest="onUpload"
>
<a-button type="primary" class="ele-btn-icon">
<template #icon>
<UploadOutlined />
</template>
<span>上传图片</span>
<span>上传素材</span>
</a-button>
</a-upload>
<a-button
@@ -37,6 +38,19 @@
</template>
<span>删除</span>
</a-button>
<a-select
v-model:value="category"
style="width: 120px"
@change="reload()"
>
<a-select-option
v-for="item in MEDIA_CATEGORY_OPTIONS"
:key="item.value"
:value="item.value"
>
{{ item.label }}
</a-select-option>
</a-select>
<a-input-search
allow-clear
v-model:value="searchText"
@@ -60,7 +74,23 @@
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'path'">
<a-image :src="record.url" :width="120" />
<!-- 与网格视图同一套 4:3 缩略图规则 -->
<div class="media-thumb" @click="openPreview(record)">
<a-image
v-if="kindOf(record) === 'image'"
:src="record.thumbnail || record.url"
:preview="{ src: record.url }"
:width="120"
/>
<template v-else>
<component
:is="iconOf(record)"
class="media-thumb-icon"
:style="{ color: colorOf(record) }"
/>
<span class="media-thumb-ext">{{ extOf(record) }}</span>
</template>
</div>
</template>
<template v-if="column.dataIndex === 'name'">
<span>{{ record.name }}</span>
@@ -78,7 +108,7 @@
<a-divider type="vertical" />
<a-popconfirm
placement="topRight"
title="确定要删除此评价吗?"
title="确定要删除此素材吗?"
@confirm="remove(record)"
>
<a class="ele-text-danger">删除</a>
@@ -90,6 +120,8 @@
</a-card>
<!-- 编辑弹窗 -->
<PhotoEdit v-model:visible="showEdit" :data="current" @done="reload" />
<!-- 音视频预览 -->
<MediaPreview v-model:visible="showPreview" :record="current" />
</div>
</template>
@@ -109,6 +141,7 @@
} from 'ele-admin-pro/es/ele-pro-table/types';
import { messageLoading, toDateString } from 'ele-admin-pro/es';
import PhotoEdit from './components/photo-edit.vue';
import MediaPreview from './components/media-preview.vue';
import {
pageFiles,
removeFile,
@@ -119,17 +152,33 @@
FileRecord,
FileRecordParam
} from '@/api/system/file/model/index';
import {
formatFileSize,
mediaColor,
mediaExtLabel,
mediaIcon,
mediaKindOfRecord,
MEDIA_ACCEPT,
MEDIA_CATEGORY_OPTIONS,
MEDIA_KIND_LABEL,
validateMediaFile,
type MediaKind
} from '@/utils/media';
// 表格实例
const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
// 表格选中数据
const selection = ref<FileRecord[]>([]);
// 当前编辑数据
// 当前操作的数据(编辑 / 预览共用)
const current = ref<FileRecord | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
// 是否显示音视频预览
const showPreview = ref(false);
const type = ref('name');
const searchText = ref('');
// 媒体大类筛选,空串表示全部
const category = ref('');
// 表格列配置
const columns = ref<ColumnItem[]>([
{
@@ -141,11 +190,17 @@
customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
},
{
title: '图片',
title: '缩略图',
dataIndex: 'path',
width: 180,
width: 140,
key: 'path'
},
{
title: '类型',
dataIndex: 'contentType',
width: 100,
customRender: ({ record }) => MEDIA_KIND_LABEL[kindOf(record)]
},
{
title: '文件名称',
dataIndex: 'name'
@@ -161,26 +216,16 @@
sorter: true,
showSorterTooltip: false,
ellipsis: true,
customRender: ({ text }) => {
if (text < 1024) {
return text + 'B';
} else if (text < 1024 * 1024) {
return (text / 1024).toFixed(1) + 'KB';
} else if (text < 1024 * 1024 * 1024) {
return (text / 1024 / 1024).toFixed(1) + 'M';
} else {
return (text / 1024 / 1024 / 1024).toFixed(1) + 'G';
}
},
customRender: ({ text }) => formatFileSize(text),
width: 120
},
{
title: '发布者',
title: '上传人',
width: 120,
dataIndex: 'createNickname'
},
{
title: '发布时间',
title: '上传时间',
dataIndex: 'createTime',
sorter: true,
width: 180,
@@ -196,6 +241,13 @@
}
]);
const kindOf = (record: FileRecord): MediaKind => mediaKindOfRecord(record);
const iconOf = (record: FileRecord) =>
mediaIcon(kindOf(record), record.path || record.name);
const colorOf = (record: FileRecord) =>
mediaColor(kindOf(record), record.path || record.name);
const extOf = (record: FileRecord) => mediaExtLabel(record);
// 表格数据源
const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
where = {};
@@ -205,7 +257,8 @@
if (type.value == 'createNickname') {
where.createNickname = searchText.value;
}
where.contentType = 'image';
// 空串会被当成一个真实的筛选值,必须置空
where.mediaCategory = category.value || undefined;
return pageFiles({ ...where, ...orders, page, limit });
};
@@ -221,6 +274,20 @@
showEdit.value = true;
};
/* 点击缩略图:音视频开播放器,文档新窗口打开 */
const openPreview = (row: FileRecord) => {
const kind = kindOf(row);
if (kind === 'image') {
return;
}
if (kind === 'doc') {
window.open(row.url, '_blank');
return;
}
current.value = row;
showPreview.value = true;
};
/* 删除单个 */
const remove = (row: FileRecord) => {
const hide = messageLoading('请求中..', 0);
@@ -266,12 +333,9 @@
// 上传文件
const onUpload = (item) => {
const { file } = item;
if (!file.type.startsWith('image')) {
message.error('只能选择图片');
return;
}
if (file.size / 1024 / 1024 > 10) {
message.error('大小不能超过 10MB');
const error = validateMediaFile(file);
if (error) {
message.error(error);
return;
}
const hide = messageLoading({
@@ -280,7 +344,7 @@
mask: true
});
uploadFile(file)
.then((data) => {
.then(() => {
hide();
message.success('上传成功');
reload();
@@ -294,6 +358,44 @@
<script lang="ts">
export default {
name: 'VideoIndex'
name: 'PhotoList'
};
</script>
<style lang="less" scoped>
.media-thumb {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 120px;
height: 90px;
overflow: hidden;
background: #f5f6f8;
border-radius: 4px;
cursor: pointer;
:deep(.ant-image),
:deep(.ant-image-img) {
width: 100%;
height: 100%;
object-fit: cover;
}
}
.media-thumb-icon {
font-size: 28px;
}
.media-thumb-ext {
position: absolute;
right: 4px;
bottom: 4px;
padding: 0 4px;
font-size: 11px;
line-height: 16px;
color: #718096;
background: rgba(255, 255, 255, 0.9);
border-radius: 3px;
}
</style>