功能:支持全站分片上传

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
+42 -1
View File
@@ -1,4 +1,4 @@
import axios, { AxiosError } from 'axios'
import axios, { AxiosError, type AxiosProgressEvent } from 'axios'
import router from '../router'
import { message } from 'ant-design-vue'
import { ADMIN_API_BASE_URL } from '../config/api'
@@ -207,6 +207,21 @@ export interface ObjectStorageFileVO {
createTime: string
}
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
export interface ChunkUploadSessionVO {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
export const adminFileApi = {
uploadFile: (file: File) => {
const formData = new FormData()
@@ -217,6 +232,32 @@ export const adminFileApi = {
}
})
},
initChunkUpload: (data: ChunkUploadInitRequest) => {
return adminApi.post<ChunkUploadSessionVO>('/object-storage-file/upload/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return adminApi.post<boolean>('/object-storage-file/upload/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeChunkUpload: (uploadId: string) => {
return adminApi.post<ObjectStorageFileVO>('/object-storage-file/upload/complete', { uploadId }) as unknown as Promise<ObjectStorageFileVO>
},
cancelChunkUpload: (uploadId: string) => {
return adminApi.delete<boolean>(`/object-storage-file/upload/${uploadId}`)
},
getSignedUrl: (id: number) => {
return adminApi.get<string>(`/object-storage-file/get-signed-url/${id}`)
}
+42
View File
@@ -1,5 +1,21 @@
import type { AxiosProgressEvent } from 'axios'
import api from './index'
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
export interface ChunkUploadSessionVO {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
export const fileApi = {
uploadAvatar: (file: File) => {
const formData = new FormData()
@@ -10,6 +26,32 @@ export const fileApi = {
}
})
},
initAvatarChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/user/upload-avatar/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadAvatarChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return api.post<boolean>('/user/upload-avatar/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeAvatarChunkUpload: (uploadId: string) => {
return api.post<string>('/user/upload-avatar/complete', { uploadId }) as unknown as Promise<string>
},
cancelAvatarChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-avatar/${uploadId}`)
},
getSignedUrl: (fileId: number, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
+1
View File
@@ -49,6 +49,7 @@ declare module 'vue' {
AModal: typeof import('ant-design-vue/es')['Modal']
APageHeader: typeof import('ant-design-vue/es')['PageHeader']
APopconfirm: typeof import('ant-design-vue/es')['Popconfirm']
AProgress: typeof import('ant-design-vue/es')['Progress']
ARadio: typeof import('ant-design-vue/es')['Radio']
ARadioButton: typeof import('ant-design-vue/es')['RadioButton']
ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup']
+161
View File
@@ -0,0 +1,161 @@
import type { AxiosProgressEvent } from 'axios'
export interface ChunkUploadSession {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
export interface ChunkUploadApi<TResponse> {
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
uploadChunk: (
payload: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => Promise<unknown>
completeUpload: (uploadId: string) => Promise<TResponse>
cancelUpload?: (uploadId: string) => Promise<unknown>
}
export interface ChunkUploadOptions<TResponse> {
file: File
scene: string
api: ChunkUploadApi<TResponse>
preprocessFile?: (file: File) => Promise<File>
onProgress?: (percent: number) => void
}
export interface ChunkUploadResult<TResponse> {
response: TResponse
uploadId: string
processedFile: File
}
export interface ChunkUploadTask<TResponse> {
promise: Promise<ChunkUploadResult<TResponse>>
cancel: () => void
getUploadId: () => string
}
const computeFileFingerprint = async (file: File) => {
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
if (!window.crypto?.subtle) {
return btoa(unescape(encodeURIComponent(fingerprintSeed)))
}
const buffer = new TextEncoder().encode(fingerprintSeed)
const hashBuffer = await window.crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('')
}
const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileSize)
return Math.max(end - start, 0)
}
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => {
return uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
}
export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
const abortController = new AbortController()
let uploadId = ''
let cancelled = false
const cleanupCancelledSession = async () => {
if (uploadId && options.api.cancelUpload) {
await options.api.cancelUpload(uploadId).catch(() => undefined)
}
}
const promise = (async () => {
const processedFile = options.preprocessFile ? await options.preprocessFile(options.file) : options.file
const fileFingerprint = await computeFileFingerprint(processedFile)
const session = await options.api.initUpload({
fileName: processedFile.name,
fileSize: processedFile.size,
contentType: processedFile.type || 'application/octet-stream',
fileFingerprint,
scene: options.scene
})
uploadId = session.uploadId
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100))
for (let chunkIndex = 0; chunkIndex < session.totalChunks; chunkIndex++) {
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
if (uploadedChunkSet.has(chunkIndex)) {
continue
}
const start = chunkIndex * session.chunkSize
const end = Math.min(start + session.chunkSize, processedFile.size)
const chunk = processedFile.slice(start, end)
const chunkBytes = end - start
await options.api.uploadChunk(
{
uploadId: session.uploadId,
chunkIndex,
totalChunks: session.totalChunks,
chunk
},
{
signal: abortController.signal,
onUploadProgress: (event) => {
const loaded = Math.min(event.loaded || 0, chunkBytes)
const percent = ((uploadedBytes + loaded) / Math.max(processedFile.size, 1)) * 100
options.onProgress?.(Math.min(percent, 99.9))
}
}
)
uploadedChunkSet.add(chunkIndex)
uploadedBytes += chunkBytes
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9))
}
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
const response = await options.api.completeUpload(session.uploadId)
options.onProgress?.(100)
return {
response,
uploadId: session.uploadId,
processedFile
}
})()
return {
promise,
cancel: () => {
cancelled = true
abortController.abort()
if (uploadId && options.api.cancelUpload) {
void options.api.cancelUpload(uploadId).catch(() => undefined)
}
},
getUploadId: () => uploadId
}
}
+1 -1
View File
@@ -87,7 +87,7 @@ const drawImageToCanvas = (image: HTMLImageElement, width: number, height: numbe
const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
type: mimeType,
lastModified: Date.now()
lastModified: sourceFile.lastModified
})
}
+74 -5
View File
@@ -125,6 +125,7 @@
@ok="handleSaveProfile"
@cancel="handleCancelEdit"
:confirmLoading="saving"
:ok-button-props="{ disabled: avatarUploadPending }"
>
<a-form layout="vertical">
<a-form-item label="头像">
@@ -139,6 +140,14 @@
<a-avatar :size="80" :src="editForm.avatar || DEFAULT_AVATAR" />
<div class="upload-hint">点击更换头像</div>
</a-upload>
<a-progress
v-if="avatarUploadPending"
:percent="Math.round(avatarUploadProgress)"
size="small"
status="active"
class="avatar-upload-progress"
/>
<div v-if="avatarUploadPending" class="avatar-upload-status">头像上传中,上传完成前不可保存。</div>
<a-button v-if="editForm.avatar" type="text" danger size="small" @click="handleDeleteAvatar">
删除头像
</a-button>
@@ -194,6 +203,7 @@ import { couponApi } from '@/api/coupon'
import { fileApi } from '@/api/file'
import { orderApi } from '@/api/order'
import { userApi, type UserVO } from '@/api/user'
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { wishlistApi } from '@/api/wishlist'
import { DEFAULT_AVATAR } from '@/constants'
@@ -220,6 +230,9 @@ const wishlistCount = ref(0)
const shopSwitchVisible = ref(false)
const shopSwitchLoading = ref(false)
const selectedShopId = ref<string>()
const avatarUploadProgress = ref(0)
const avatarUploadPending = ref(false)
let avatarUploadTask: ChunkUploadTask<string> | null = null
const editForm = reactive({
nickname: '',
@@ -325,6 +338,10 @@ const loadCounts = async () => {
}
const handleEditProfile = () => {
avatarUploadTask?.cancel()
avatarUploadTask = null
avatarUploadPending.value = false
avatarUploadProgress.value = 0
editForm.nickname = userInfo.value.nickname || ''
editForm.avatar = userInfo.value.avatar || ''
editForm.signature = userInfo.value.signature || ''
@@ -345,14 +362,47 @@ const beforeUploadAvatar: UploadProps['beforeUpload'] = file => {
}
const handleAvatarUpload = async (options: any) => {
const { file } = options
const { file, onProgress, onSuccess, onError } = options
avatarUploadTask?.cancel()
avatarUploadProgress.value = 0
avatarUploadPending.value = true
const task = createChunkUploadTask({
file: file as File,
scene: 'profile-avatar',
api: {
initUpload: fileApi.initAvatarChunkUpload,
uploadChunk: fileApi.uploadAvatarChunk,
completeUpload: fileApi.completeAvatarChunkUpload,
cancelUpload: fileApi.cancelAvatarChunkUpload
},
onProgress: (percent) => {
avatarUploadProgress.value = percent
onProgress?.({ percent })
}
})
avatarUploadTask = task
try {
const res = await fileApi.uploadAvatar(file)
editForm.avatar = res as unknown as string
const { response } = await task.promise
editForm.avatar = response as unknown as string
avatarUploadProgress.value = 100
onSuccess?.({ url: response })
message.success('头像上传成功')
} catch (error) {
console.error('头像上传失败:', error)
message.error('头像上传失败')
const errorMessage = (error as Error)?.message || '头像上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('头像上传失败:', error)
message.error(errorMessage)
onError?.(error)
}
} finally {
if (avatarUploadTask === task) {
avatarUploadTask = null
avatarUploadPending.value = false
}
}
}
@@ -382,6 +432,11 @@ const handleSaveProfile = async () => {
return
}
if (avatarUploadPending.value) {
message.warning('头像上传完成前不可保存')
return
}
saving.value = true
try {
await userApi.updateUserInfo({
@@ -401,6 +456,10 @@ const handleSaveProfile = async () => {
}
const handleCancelEdit = () => {
avatarUploadTask?.cancel()
avatarUploadTask = null
avatarUploadPending.value = false
avatarUploadProgress.value = 0
editModalVisible.value = false
}
@@ -725,6 +784,16 @@ onMounted(async () => {
color: #667eea;
}
.avatar-upload-progress {
width: 220px;
margin-top: 4px;
}
.avatar-upload-status {
font-size: 12px;
color: #fa8c16;
}
.shop-option-group {
display: flex;
flex-direction: column;
+77 -28
View File
@@ -89,6 +89,7 @@
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
:ok-button-props="{ disabled: isUploadPending }"
>
<a-form
ref="formRef"
@@ -150,6 +151,7 @@
</div>
</a-upload>
<div class="upload-tip">支持多选上传,单张图片超过 5MB 会自动压缩后再上传。</div>
<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>
@@ -362,11 +364,12 @@
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { computed, ref, reactive, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import { adminProductApi, type Product, adminShopApi, type Shop, adminFileApi, adminTagApi, adminArtistApi, adminCouponApi } from '@/api/admin'
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { usePermission } from '@/utils/permission'
import { MAX_IMAGE_UPLOAD_SIZE, compressImageIfNeeded, formatFileSize } from '@/utils/image-upload'
@@ -397,6 +400,9 @@ const imageIdCache = ref<Record<string, string>>({})
const isAdmin = ref(false)
const formRef = ref<any>(null)
const MAX_PRODUCT_IMAGE_COUNT = 5
const uploadTaskMap = new Map<string, ChunkUploadTask<any>>()
const activeUploadCount = ref(0)
const isUploadPending = computed(() => activeUploadCount.value > 0)
const viewFormState = reactive({
shopId: undefined,
@@ -805,6 +811,10 @@ const handleViewModalCancel = () => {
viewImageUrls.value = []
}
const cancelAllPendingUploads = () => {
uploadTaskMap.forEach(task => task.cancel())
}
const syncUploadedFileIds = (fileIds: string[]) => {
uploadedFileIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
formState.imageFileIds = uploadedFileIds.value.join(',')
@@ -860,37 +870,58 @@ const beforeUpload = (file: File) => {
}
const handleUploadImage = async (options: any) => {
const { file, onSuccess, onError } = options
const { file, onSuccess, onError, onProgress } = options
let successMessage = '图片上传成功'
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-product-image',
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
preprocessFile: async (originalFile) => {
const compressedResult = await compressImageIfNeeded(originalFile, MAX_IMAGE_UPLOAD_SIZE)
if (compressedResult.skippedReason) {
throw new Error(compressedResult.skippedReason)
}
if (compressedResult.finalSize > MAX_IMAGE_UPLOAD_SIZE) {
throw new Error('图片压缩后仍超过 5MB,请裁剪后重试')
}
if (compressedResult.compressed && compressedResult.originalSize !== compressedResult.finalSize) {
successMessage = `${originalFile.name} 已压缩并上传成功(${formatFileSize(compressedResult.originalSize)} -> ${formatFileSize(compressedResult.finalSize)})`
}
return compressedResult.file
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
uploadTaskMap.set(String(file.uid), task)
activeUploadCount.value += 1
try {
const originalFile = file as File
const compressedResult = await compressImageIfNeeded(originalFile, MAX_IMAGE_UPLOAD_SIZE)
if (compressedResult.skippedReason) {
throw new Error(compressedResult.skippedReason)
}
if (compressedResult.finalSize > MAX_IMAGE_UPLOAD_SIZE) {
throw new Error('图片压缩后仍超过 5MB,请裁剪后重试')
}
const response = await adminFileApi.uploadFile(compressedResult.file) as any
const fileId = String(response.id)
const { response } = await task.promise
const fileId = String((response as any).id)
syncUploadedFileIds([...uploadedFileIds.value, fileId])
onSuccess?.({ id: fileId, fileId })
if (compressedResult.compressed && compressedResult.originalSize !== compressedResult.finalSize) {
message.success(
`${originalFile.name} 已压缩并上传成功(${formatFileSize(compressedResult.originalSize)} -> ${formatFileSize(compressedResult.finalSize)})`
)
return
}
message.success('图片上传成功')
message.success(successMessage)
} catch (error) {
console.error('图片上传失败:', error)
onError?.(error)
message.error((error as Error)?.message || '图片上传失败')
const errorMessage = (error as Error)?.message || '图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error)
message.error(errorMessage)
onError?.(error)
}
} finally {
uploadTaskMap.delete(String(file.uid))
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
}
}
@@ -922,6 +953,12 @@ const handlePreview = async (file: any) => {
}
const handleRemove = (file: any) => {
const uploadTask = uploadTaskMap.get(String(file.uid))
if (uploadTask) {
uploadTask.cancel()
return true
}
const fileId = resolveUploadedFileId(file)
if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
@@ -932,6 +969,10 @@ const handleRemove = (file: any) => {
const handleModalOk = async () => {
try {
if (isUploadPending.value) {
message.warning('图片上传完成前不可提交')
return
}
await formRef.value?.validate()
modalLoading.value = true
@@ -974,6 +1015,7 @@ const handleModalOk = async () => {
}
const handleModalCancel = () => {
cancelAllPendingUploads()
modalVisible.value = false
formRef.value?.resetFields()
}
@@ -1034,4 +1076,11 @@ watch(() => formState.shopId, (newShopId) => {
line-height: 1.6;
margin-top: 8px;
}
.upload-pending-tip {
color: #fa8c16;
font-size: 12px;
line-height: 1.6;
margin-top: 6px;
}
</style>
+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;