功能:支持全站分片上传

This commit is contained in:
xiaowang
2026-03-26 11:41:38 +08:00
parent 0959f14555
commit b4042b3560
18 changed files with 1324 additions and 90 deletions
+208 -51
View File
@@ -103,6 +103,7 @@
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
:ok-button-props="{ disabled: isUploadPending }"
>
<a-form
ref="formRef"
@@ -165,6 +166,7 @@
<div style="margin-top: 8px">上传Banner</div>
</div>
</a-upload>
<div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div>
<a-modal v-model:open="bannerPreviewVisible" :footer="null" @cancel="bannerPreviewVisible = false">
<img alt="预览" style="width: 100%" :src="bannerPreviewImage" />
</a-modal>
@@ -185,6 +187,7 @@
<div style="margin-top: 8px">上传图片</div>
</div>
</a-upload>
<div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div>
<a-modal v-model:open="previewVisible" :footer="null" @cancel="previewVisible = false">
<img alt="预览" style="width: 100%" :src="previewImage" />
</a-modal>
@@ -261,12 +264,13 @@
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { computed, ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { DEFAULT_SHOP_IMAGE } from '@/constants'
import { adminShopApi, adminFileApi, type Shop } from '@/api/admin'
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { usePermission } from '@/utils/permission'
const { hasPermission, loadUserPermissions } = usePermission()
@@ -300,6 +304,9 @@ const previewVisible = ref(false)
const previewImage = ref('')
const businessStartTime = ref('')
const businessEndTime = ref('')
const uploadTaskMap = new Map<string, ChunkUploadTask<any>>()
const activeUploadCount = ref(0)
const isUploadPending = computed(() => activeUploadCount.value > 0)
// 查看店铺相关状态
const viewFormState = reactive({
@@ -509,82 +516,162 @@ const beforeUpload = (file: File) => {
// Banner图片上传
const handleUploadBanner = async (options: any) => {
const { file, onSuccess, onError } = options
const { file, onSuccess, onError, onProgress } = options
const taskKey = `banner:${String(file.uid)}`
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-shop-banner',
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
uploadTaskMap.set(taskKey, task)
activeUploadCount.value += 1
try {
const response = await adminFileApi.uploadFile(file)
const res = typeof response === 'object' && 'id' in response ? response : (response as any).data
uploadedBannerIds.value.push(String(res.id))
formState.coverImageFileId = uploadedBannerIds.value.join(',')
onSuccess({ url: String(res.id) })
const { response } = await task.promise
const fileId = String((response as any).id)
syncUploadedBannerIds([...uploadedBannerIds.value, fileId])
onSuccess?.({ id: fileId, fileId })
message.success('Banner上传成功')
} catch (error) {
console.error('Banner上传失败:', error)
onError(error)
message.error('Banner上传失败')
const errorMessage = (error as Error)?.message || 'Banner上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('Banner上传失败:', error)
message.error(errorMessage)
onError?.(error)
}
} finally {
uploadTaskMap.delete(taskKey)
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
}
}
const handleBannerPreview = async (file: any) => {
try {
// 检查缓存
if (!imageIdCache.value[file.uid]) {
const response = await adminFileApi.getSignedUrl(Number(file.uid)) as any
imageIdCache.value[file.uid] = response
const cachedPreviewUrl = getPreviewUrlFromFile(file)
if (cachedPreviewUrl) {
bannerPreviewImage.value = cachedPreviewUrl
bannerPreviewVisible.value = true
return
}
bannerPreviewImage.value = imageIdCache.value[file.uid] || ''
const fileId = resolveUploadedFileId(file)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
if (!imageIdCache.value[fileId]) {
const response = await adminFileApi.getSignedUrl(Number(fileId)) as any
imageIdCache.value[fileId] = response
}
bannerPreviewImage.value = imageIdCache.value[fileId] || ''
bannerPreviewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
message.error('获取预览链接失败')
message.error((error as Error)?.message || '获取预览链接失败')
}
}
const handleBannerRemove = (file: any) => {
const index = uploadedBannerIds.value.indexOf(file.uid)
if (index > -1) {
uploadedBannerIds.value.splice(index, 1)
formState.coverImageFileId = uploadedBannerIds.value.join(',')
const task = uploadTaskMap.get(`banner:${String(file.uid)}`)
if (task) {
task.cancel()
return true
}
const fileId = resolveUploadedFileId(file)
if (fileId) {
syncUploadedBannerIds(uploadedBannerIds.value.filter(id => id !== fileId))
}
return true
}
// 店铺图片上传
const handleUploadImage = async (options: any) => {
const { file, onSuccess, onError } = options
const { file, onSuccess, onError, onProgress } = options
const taskKey = `image:${String(file.uid)}`
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-shop-image',
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
uploadTaskMap.set(taskKey, task)
activeUploadCount.value += 1
try {
const response = await adminFileApi.uploadFile(file)
const res = typeof response === 'object' && 'id' in response ? response : (response as any).data
uploadedFileIds.value.push(String(res.id))
formState.imageFileIds = uploadedFileIds.value.join(',')
onSuccess({ url: String(res.id) })
const { response } = await task.promise
const fileId = String((response as any).id)
syncUploadedFileIds([...uploadedFileIds.value, fileId])
onSuccess?.({ id: fileId, fileId })
message.success('图片上传成功')
} catch (error) {
console.error('图片上传失败:', error)
onError(error)
message.error('图片上传失败')
const errorMessage = (error as Error)?.message || '图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error)
message.error(errorMessage)
onError?.(error)
}
} finally {
uploadTaskMap.delete(taskKey)
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
}
}
const handlePreview = async (file: any) => {
try {
// 检查缓存
if (!imageIdCache.value[file.uid]) {
const response = await adminFileApi.getSignedUrl(Number(file.uid)) as any
imageIdCache.value[file.uid] = response
const cachedPreviewUrl = getPreviewUrlFromFile(file)
if (cachedPreviewUrl) {
previewImage.value = cachedPreviewUrl
previewVisible.value = true
return
}
previewImage.value = imageIdCache.value[file.uid] || ''
const fileId = resolveUploadedFileId(file)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
if (!imageIdCache.value[fileId]) {
const response = await adminFileApi.getSignedUrl(Number(fileId)) as any
imageIdCache.value[fileId] = response
}
previewImage.value = imageIdCache.value[fileId] || ''
previewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
message.error('获取预览链接失败')
message.error((error as Error)?.message || '获取预览链接失败')
}
}
const handleRemove = (file: any) => {
const index = uploadedFileIds.value.indexOf(file.uid)
if (index > -1) {
uploadedFileIds.value.splice(index, 1)
formState.imageFileIds = uploadedFileIds.value.join(',')
const task = uploadTaskMap.get(`image:${String(file.uid)}`)
if (task) {
task.cancel()
return true
}
const fileId = resolveUploadedFileId(file)
if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
}
return true
}
const syncBusinessHoursValue = () => {
@@ -618,9 +705,9 @@ const showAddModal = () => {
})
setBusinessHoursValue('')
bannerFileList.value = []
uploadedBannerIds.value = []
syncUploadedBannerIds([])
imageFileList.value = []
uploadedFileIds.value = []
syncUploadedFileIds([])
modalVisible.value = true
}
@@ -641,8 +728,8 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
// 加载Banner图片
const coverImageFileId = 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId
if (coverImageFileId) {
const ids = coverImageFileId.split(',')
uploadedBannerIds.value = ids
const ids = coverImageFileId.split(',').filter((id: string) => id)
syncUploadedBannerIds(ids)
// 加载所有图片签名链接
const fileList = []
@@ -655,6 +742,7 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
}
fileList.push({
uid: id,
fileId: id,
name: `Banner${index + 1}`,
status: 'done',
url: imageIdCache.value[id]
@@ -663,6 +751,7 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
console.error('获取签名链接失败:', error)
fileList.push({
uid: id,
fileId: id,
name: `Banner${index + 1}`,
status: 'done',
url: ''
@@ -672,14 +761,14 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
bannerFileList.value = fileList
} else {
bannerFileList.value = []
uploadedBannerIds.value = []
syncUploadedBannerIds([])
}
// 加载店铺图片
const imageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
if (imageFileIds) {
const ids = imageFileIds.split(',')
uploadedFileIds.value = ids
const ids = imageFileIds.split(',').filter((id: string) => id)
syncUploadedFileIds(ids)
// 加载所有图片签名链接
const fileList = []
@@ -692,6 +781,7 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
}
fileList.push({
uid: id,
fileId: id,
name: `图片${index + 1}`,
status: 'done',
url: imageIdCache.value[id]
@@ -700,6 +790,7 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
console.error('获取签名链接失败:', error)
fileList.push({
uid: id,
fileId: id,
name: `图片${index + 1}`,
status: 'done',
url: ''
@@ -709,7 +800,7 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
imageFileList.value = fileList
} else {
imageFileList.value = []
uploadedFileIds.value = []
syncUploadedFileIds([])
}
modalVisible.value = true
@@ -729,7 +820,7 @@ const showViewModal = async (record: Shop | Record<string, any>) => {
// 加载Banner图片URL
const coverImageFileId = 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId
if (coverImageFileId) {
const ids = coverImageFileId.split(',')
const ids = coverImageFileId.split(',').filter((id: string) => id)
const urls: string[] = []
for (const id of ids) {
@@ -753,7 +844,7 @@ const showViewModal = async (record: Shop | Record<string, any>) => {
// 加载店铺图片URL
const imageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
if (imageFileIds) {
const ids = imageFileIds.split(',')
const ids = imageFileIds.split(',').filter((id: string) => id)
const urls: string[] = []
for (const id of ids) {
@@ -783,8 +874,67 @@ const handleViewModalCancel = () => {
viewBannerUrls.value = []
}
const cancelAllPendingUploads = () => {
uploadTaskMap.forEach(task => task.cancel())
}
const syncUploadedBannerIds = (fileIds: string[]) => {
uploadedBannerIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
formState.coverImageFileId = uploadedBannerIds.value.join(',')
}
const syncUploadedFileIds = (fileIds: string[]) => {
uploadedFileIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
formState.imageFileIds = uploadedFileIds.value.join(',')
}
const getUploadResponse = (file: any) => {
if (!file || typeof file !== 'object') {
return null
}
return file.response || null
}
const resolveUploadedFileId = (file: any) => {
const response = getUploadResponse(file)
const responseId = response?.id ?? response?.data?.id ?? file?.fileId
if (responseId !== undefined && responseId !== null && responseId !== '') {
return String(responseId)
}
const fileUid = String(file?.uid || '')
if (/^\d+$/.test(fileUid)) {
return fileUid
}
const fileUrl = String(file?.url || '')
if (/^\d+$/.test(fileUrl)) {
return fileUrl
}
return ''
}
const getPreviewUrlFromFile = (file: any) => {
const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) {
return fileUrl
}
const thumbUrl = typeof file?.thumbUrl === 'string' ? file.thumbUrl : ''
if (thumbUrl) {
return thumbUrl
}
return ''
}
const handleModalOk = async () => {
try {
if (isUploadPending.value) {
message.warning('图片上传完成前不可提交')
return
}
syncBusinessHoursValue()
await formRef.value?.validate()
modalLoading.value = true
@@ -807,13 +957,14 @@ const handleModalOk = async () => {
}
const handleModalCancel = () => {
cancelAllPendingUploads()
modalVisible.value = false
formRef.value?.resetFields()
setBusinessHoursValue('')
bannerFileList.value = []
uploadedBannerIds.value = []
syncUploadedBannerIds([])
imageFileList.value = []
uploadedFileIds.value = []
syncUploadedFileIds([])
}
const handleDelete = async (record: Shop | Record<string, any>) => {
@@ -874,6 +1025,12 @@ onMounted(async () => {
margin-bottom: 8px;
}
.upload-pending-tip {
color: #fa8c16;
font-size: 12px;
margin-top: 8px;
}
.business-hours-picker {
display: flex;
align-items: center;