feat: 素材管理迁移

This commit is contained in:
dylanmay
2025-11-04 17:32:12 +08:00
parent 2153b1325c
commit c238920588
8 changed files with 941 additions and 22 deletions

View File

@@ -0,0 +1,85 @@
<script lang="ts" setup>
import { useAccess } from '@vben/access';
import { IconifyIcon } from '@vben/icons';
import { Spin } from 'ant-design-vue';
const props = defineProps<{
list: any[];
loading: boolean;
}>();
const emit = defineEmits<{
delete: [v: number];
}>();
const { hasAccessByCodes } = useAccess();
</script>
<template>
<Spin :spinning="props.loading">
<div class="waterfall">
<div v-for="item in props.list" :key="item.id" class="waterfall-item">
<a :href="item.url" target="_blank">
<img :src="item.url" class="material-img" />
<div class="item-name">{{ item.name }}</div>
</a>
<div class="flex justify-center">
<a-button
v-if="hasAccessByCodes(['mp:material:delete'])"
danger
shape="circle"
type="primary"
@click="emit('delete', item.id)"
>
<template #icon>
<IconifyIcon icon="mdi:delete" />
</template>
</a-button>
</div>
</div>
</div>
</Spin>
</template>
<style lang="scss" scoped>
@media (width >= 992px) and (width <= 1300px) {
.waterfall {
column-count: 3;
}
}
@media (width >= 768px) and (width <= 991px) {
.waterfall {
column-count: 2;
}
}
@media (width <= 767px) {
.waterfall {
column-count: 1;
}
}
.waterfall {
column-gap: 10px;
width: 100%;
margin-top: 10px;
column-count: 5;
}
.waterfall-item {
padding: 10px;
margin-bottom: 10px;
border: 1px solid #eaeaea;
break-inside: avoid;
}
.material-img {
width: 100%;
}
.item-name {
line-height: 30px;
}
</style>

View File

@@ -0,0 +1,108 @@
<script lang="ts" setup>
import type { UploadProps } from 'ant-design-vue';
import type { UploadData } from './upload';
import { inject, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { message, Upload } from 'ant-design-vue';
import {
beforeImageUpload,
beforeVoiceUpload,
HEADERS,
UPLOAD_URL,
UploadType,
} from './upload';
const props = defineProps<{ type: UploadType }>();
const emit = defineEmits<{
uploaded: [v: void];
}>();
const accountId = inject<number>('accountId');
const fileList = ref<any[]>([]);
const uploadData: UploadData = reactive({
accountId: accountId!,
introduction: '',
title: '',
type: props.type,
});
/** 上传前检查 */
const onBeforeUpload =
props.type === UploadType.Image ? beforeImageUpload : beforeVoiceUpload;
/** 自定义上传 */
const customRequest: UploadProps['customRequest'] = async (options) => {
const { file, onError, onSuccess } = options;
const formData = new FormData();
formData.append('file', file as File);
formData.append('type', uploadData.type);
formData.append('title', uploadData.title);
formData.append('introduction', uploadData.introduction);
formData.append('accountId', String(uploadData.accountId));
try {
const response = await fetch(UPLOAD_URL, {
body: formData,
headers: HEADERS,
method: 'POST',
});
const res = await response.json();
if (res.code !== 0) {
message.error(`上传出错:${res.msg}`);
onError?.(new Error(res.msg));
return;
}
// 清空上传时的各种数据
fileList.value = [];
uploadData.title = '';
uploadData.introduction = '';
message.success('上传成功');
onSuccess?.(res);
emit('uploaded');
} catch (error: any) {
message.error(`上传失败: ${error.message}`);
onError?.(error);
}
};
</script>
<template>
<Upload
:action="UPLOAD_URL"
:before-upload="onBeforeUpload"
:custom-request="customRequest"
:data="uploadData"
:file-list="fileList"
:headers="HEADERS"
:multiple="true"
class="mb-4"
>
<a-button type="primary">
<IconifyIcon icon="mdi:upload" class="mr-1" />
点击上传
</a-button>
<template #itemRender="{ file, actions }">
<div class="flex items-center">
<span>{{ file.name }}</span>
<a-button type="link" size="small" @click="actions.remove">
删除
</a-button>
</div>
</template>
</Upload>
<div v-if="$slots.default" class="ml-1 text-sm text-gray-500">
<slot></slot>
</div>
</template>

View File

@@ -0,0 +1,154 @@
<script lang="ts" setup>
import type { FormInstance, UploadProps } from 'ant-design-vue';
import type { UploadData } from './upload';
import { inject, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { message, Modal, Upload } from 'ant-design-vue';
import { beforeVideoUpload, HEADERS, UPLOAD_URL, UploadType } from './upload';
withDefaults(
defineProps<{
open?: boolean;
}>(),
{
open: false,
},
);
const emit = defineEmits<{
'update:open': [v: boolean];
uploaded: [v: void];
}>();
const accountId = inject<number>('accountId');
const uploadRules = {
introduction: [{ message: '请输入描述', required: true, trigger: 'blur' }],
title: [{ message: '请输入标题', required: true, trigger: 'blur' }],
};
const handleCancel = () => {
emit('update:open', false);
};
const fileList = ref<any[]>([]);
const uploadData: UploadData = reactive({
accountId: accountId!,
introduction: '',
title: '',
type: UploadType.Video,
});
const uploadFormRef = ref<FormInstance | null>(null);
const uploadVideoRef = ref<any>(null);
const submitVideo = async () => {
try {
await uploadFormRef.value?.validate();
uploadVideoRef.value?.submit();
} catch {
// Validation failed
}
};
/** 自定义上传 */
const customRequest: UploadProps['customRequest'] = async (options) => {
const { file, onError, onSuccess } = options;
const formData = new FormData();
formData.append('file', file as File);
formData.append('type', uploadData.type);
formData.append('title', uploadData.title);
formData.append('introduction', uploadData.introduction);
formData.append('accountId', String(uploadData.accountId));
try {
const response = await fetch(UPLOAD_URL, {
body: formData,
headers: HEADERS,
method: 'POST',
});
const res = await response.json();
if (res.code !== 0) {
message.error(`上传出错:${res.msg}`);
onError?.(new Error(res.msg));
return;
}
// 清空上传时的各种数据
fileList.value = [];
uploadData.title = '';
uploadData.introduction = '';
emit('update:open', false);
message.success('上传成功');
onSuccess?.(res);
emit('uploaded');
} catch (error: any) {
message.error(`上传失败: ${error.message}`);
onError?.(error);
}
};
</script>
<template>
<Modal
:open="open"
title="新建视频"
width="600px"
@cancel="handleCancel"
@ok="submitVideo"
>
<Upload
ref="uploadVideoRef"
:action="UPLOAD_URL"
:auto-upload="false"
:before-upload="beforeVideoUpload"
:custom-request="customRequest"
:file-list="fileList"
:headers="HEADERS"
:limit="1"
:multiple="true"
class="mb-4"
>
<a-button type="primary">
<IconifyIcon icon="mdi:video-plus" class="mr-1" />
选择视频
</a-button>
</Upload>
<div class="mb-4 ml-1 text-sm text-gray-500">
格式支持 MP4文件大小不超过 10MB
</div>
<a-divider />
<a-form
ref="uploadFormRef"
:model="uploadData"
:rules="uploadRules"
layout="vertical"
>
<a-form-item label="标题" name="title">
<a-input
v-model:value="uploadData.title"
placeholder="标题将展示在相关播放页面,建议填写清晰、准确、生动的标题"
/>
</a-form-item>
<a-form-item label="描述" name="introduction">
<a-textarea
v-model:value="uploadData.introduction"
:rows="3"
placeholder="介绍语将展示在相关播放页面,建议填写简洁明确、有信息量的内容"
/>
</a-form-item>
</a-form>
</Modal>
</template>

View File

@@ -0,0 +1,74 @@
<script lang="ts" setup>
import { useAccess } from '@vben/access';
import { IconifyIcon } from '@vben/icons';
import { formatDate2 } from '@vben/utils';
import WxVideoPlayer from '#/views/mp/components/wx-video-play';
const props = defineProps<{
list: any[];
loading: boolean;
}>();
const emit = defineEmits<{
delete: [v: number];
}>();
const { hasAccessByCodes } = useAccess();
const columns = [
{ align: 'center', dataIndex: 'mediaId', key: 'mediaId', title: '编号' },
{ align: 'center', dataIndex: 'name', key: 'name', title: '文件名' },
{ align: 'center', dataIndex: 'title', key: 'title', title: '标题' },
{
align: 'center',
dataIndex: 'introduction',
key: 'introduction',
title: '介绍',
},
{ align: 'center', key: 'video', title: '视频' },
{ align: 'center', key: 'createTime', title: '上传时间', width: 180 },
{ align: 'center', fixed: 'right', key: 'action', title: '操作' },
];
// 下载文件
const handleDownload = (url: string) => {
window.open(url, '_blank');
};
</script>
<template>
<a-table
:columns="columns"
:data-source="props.list"
:loading="props.loading"
:pagination="false"
bordered
class="mt-4"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'video'">
<WxVideoPlayer v-if="record.url" :url="record.url" />
</template>
<template v-else-if="column.key === 'createTime'">
{{ formatDate2(record.createTime) }}
</template>
<template v-else-if="column.key === 'action'">
<a-button type="link" @click="handleDownload(record.url)">
<IconifyIcon icon="mdi:download" />
下载
</a-button>
<a-button
v-if="hasAccessByCodes(['mp:material:delete'])"
danger
type="link"
@click="emit('delete', record.id)"
>
<IconifyIcon icon="mdi:delete" />
删除
</a-button>
</template>
</template>
</a-table>
</template>

View File

@@ -0,0 +1,66 @@
<script lang="ts" setup>
import { useAccess } from '@vben/access';
import { IconifyIcon } from '@vben/icons';
import { formatDate2 } from '@vben/utils';
import WxVoicePlayer from '#/views/mp/components/wx-voice-play';
const props = defineProps<{
list: any[];
loading: boolean;
}>();
const emit = defineEmits<{
delete: [v: number];
}>();
const { hasAccessByCodes } = useAccess();
const columns = [
{ align: 'center', dataIndex: 'mediaId', key: 'mediaId', title: '编号' },
{ align: 'center', dataIndex: 'name', key: 'name', title: '文件名' },
{ align: 'center', key: 'voice', title: '语音' },
{ align: 'center', key: 'createTime', title: '上传时间', width: 180 },
{ align: 'center', fixed: 'right', key: 'action', title: '操作' },
];
const handleDownload = (url: string) => {
window.open(url, '_blank');
};
</script>
<template>
<a-table
:columns="columns"
:data-source="props.list"
:loading="props.loading"
:pagination="false"
bordered
class="mt-4"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'voice'">
<WxVoicePlayer v-if="record.url" :url="record.url" />
</template>
<template v-else-if="column.key === 'createTime'">
{{ formatDate2(record.createTime) }}
</template>
<template v-else-if="column.key === 'action'">
<a-button type="link" @click="handleDownload(record.url)">
<IconifyIcon icon="mdi:download" />
下载
</a-button>
<a-button
v-if="hasAccessByCodes(['mp:material:delete'])"
danger
type="link"
@click="emit('delete', record.id)"
>
<IconifyIcon icon="mdi:delete" />
删除
</a-button>
</template>
</template>
</a-table>
</template>

View File

@@ -0,0 +1,40 @@
import type { UploadProps } from 'ant-design-vue';
import type { UploadRawFile } from '#/views/mp/hooks/useUpload';
import { useAccessStore } from '@vben/stores';
import { UploadType, useBeforeUpload } from '#/views/mp/hooks/useUpload';
const accessStore = useAccessStore();
const HEADERS = { Authorization: `Bearer ${accessStore.accessToken}` }; // 请求头
const UPLOAD_URL = `${import.meta.env.VITE_BASE_URL}/admin-api/mp/material/upload-permanent`; // 上传地址
interface UploadData {
accountId: number;
introduction: string;
title: string;
type: UploadType;
}
const beforeImageUpload: UploadProps['beforeUpload'] = (
rawFile: UploadRawFile,
) => useBeforeUpload(UploadType.Image, 2)(rawFile);
const beforeVoiceUpload: UploadProps['beforeUpload'] = (
rawFile: UploadRawFile,
) => useBeforeUpload(UploadType.Voice, 2)(rawFile);
const beforeVideoUpload: UploadProps['beforeUpload'] = (
rawFile: UploadRawFile,
) => useBeforeUpload(UploadType.Video, 10)(rawFile);
export {
beforeImageUpload,
beforeVideoUpload,
beforeVoiceUpload,
HEADERS,
UPLOAD_URL,
type UploadData,
UploadType,
};

View File

@@ -1,29 +1,204 @@
<script lang="ts" setup>
import { DocAlert, Page } from '@vben/common-ui';
import { provide, reactive, ref } from 'vue';
import { Button } from 'ant-design-vue';
import { useAccess } from '@vben/access';
import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { message, Modal, Tabs } from 'ant-design-vue';
import * as MpMaterialApi from '#/api/mp/material';
import WxAccountSelect from '#/views/mp/components/wx-account-select';
import ImageTable from './components/ImageTable.vue';
import { UploadType } from './components/upload';
import UploadFile from './components/UploadFile.vue';
import UploadVideo from './components/UploadVideo.vue';
import VideoTable from './components/VideoTable.vue';
import VoiceTable from './components/VoiceTable.vue';
defineOptions({ name: 'MpMaterial' });
const { hasAccessByCodes } = useAccess();
const type = ref<UploadType>(UploadType.Image); // 素材类型
const loading = ref(false); // 遮罩层
const list = ref<any[]>([]); // 数据列表
const total = ref(0); // 总条数
const accountId = ref(-1);
provide('accountId', accountId);
// 查询参数
const queryParams = reactive({
accountId,
pageNo: 1,
pageSize: 10,
permanent: true,
});
const showCreateVideo = ref(false); // 是否新建视频的弹窗
/** 侦听公众号变化 */
const onAccountChanged = (id: number) => {
accountId.value = id;
queryParams.accountId = id;
queryParams.pageNo = 1;
getList();
};
/** 查询列表 */
const getList = async () => {
loading.value = true;
try {
const data = await MpMaterialApi.getMaterialPage({
...queryParams,
type: type.value,
});
list.value = data.list;
total.value = data.total;
} finally {
loading.value = false;
}
};
/** 搜索按钮操作 */
const handleQuery = () => {
queryParams.pageNo = 1;
getList();
};
/** 处理 tab 切换 */
const onTabChange = () => {
// 提前清空数据,避免 tab 切换后显示垃圾数据
list.value = [];
total.value = 0;
// 从第一页开始查询
handleQuery();
};
/** 处理删除操作 */
const handleDelete = async (id: number) => {
Modal.confirm({
content: '此操作将永久删除该文件, 是否继续?',
title: '提示',
async onOk() {
await MpMaterialApi.deletePermanentMaterial(id);
message.success('删除成功');
await getList();
},
});
};
</script>
<template>
<Page>
<DocAlert title="公众号素材" url="https://doc.iocoder.cn/mp/material/" />
<Button
danger
type="link"
target="_blank"
href="https://github.com/yudaocode/yudao-ui-admin-vue3"
>
该功能支持 Vue3 + element-plus 版本
</Button>
<br />
<Button
type="link"
target="_blank"
href="https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/mp/material/index"
>
可参考
https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/mp/material/index
代码pull request 贡献给我们
</Button>
<Page
description="公众号素材"
doc-link="https://doc.iocoder.cn/mp/material/"
title="公众号素材"
>
<!-- 搜索工作栏 -->
<a-card class="mb-4" :bordered="false">
<a-form :model="queryParams" layout="inline">
<a-form-item label="公众号">
<WxAccountSelect @change="onAccountChanged" />
</a-form-item>
</a-form>
</a-card>
<a-card :bordered="false">
<Tabs v-model:active-key="type" @change="onTabChange">
<!-- tab 1图片 -->
<Tabs.TabPane :key="UploadType.Image">
<template #tab>
<span class="flex items-center">
<IconifyIcon icon="mdi:image" class="mr-1" />
图片
</span>
</template>
<UploadFile
v-if="hasAccessByCodes(['mp:material:upload-permanent'])"
:type="UploadType.Image"
@uploaded="getList"
>
支持 bmp/png/jpeg/jpg/gif 格式大小不超过 2M
</UploadFile>
<!-- 列表 -->
<ImageTable :list="list" :loading="loading" @delete="handleDelete" />
<!-- 分页组件 -->
<div class="mt-4 flex justify-end">
<a-pagination
v-model:current="queryParams.pageNo"
v-model:page-size="queryParams.pageSize"
:total="total"
show-size-changer
@change="getList"
@show-size-change="getList"
/>
</div>
</Tabs.TabPane>
<!-- tab 2语音 -->
<Tabs.TabPane :key="UploadType.Voice">
<template #tab>
<span class="flex items-center">
<IconifyIcon icon="mdi:microphone" class="mr-1" />
语音
</span>
</template>
<UploadFile
v-if="hasAccessByCodes(['mp:material:upload-permanent'])"
:type="UploadType.Voice"
@uploaded="getList"
>
格式支持 mp3/wma/wav/amr文件大小不超过 2M播放长度不超过 60s
</UploadFile>
<!-- 列表 -->
<VoiceTable :list="list" :loading="loading" @delete="handleDelete" />
<!-- 分页组件 -->
<div class="mt-4 flex justify-end">
<a-pagination
v-model:current="queryParams.pageNo"
v-model:page-size="queryParams.pageSize"
:total="total"
show-size-changer
@change="getList"
@show-size-change="getList"
/>
</div>
</Tabs.TabPane>
<!-- tab 3视频 -->
<Tabs.TabPane :key="UploadType.Video">
<template #tab>
<span class="flex items-center">
<IconifyIcon icon="mdi:video" class="mr-1" />
视频
</span>
</template>
<a-button
v-if="hasAccessByCodes(['mp:material:upload-permanent'])"
type="primary"
@click="showCreateVideo = true"
>
新建视频
</a-button>
<!-- 新建视频的弹窗 -->
<UploadVideo v-model:open="showCreateVideo" @uploaded="getList" />
<!-- 列表 -->
<VideoTable :list="list" :loading="loading" @delete="handleDelete" />
<!-- 分页组件 -->
<div class="mt-4 flex justify-end">
<a-pagination
v-model:current="queryParams.pageNo"
v-model:page-size="queryParams.pageSize"
:total="total"
show-size-changer
@change="getList"
@show-size-change="getList"
/>
</div>
</Tabs.TabPane>
</Tabs>
</a-card>
</Page>
</template>