功能:支持全站分片上传
This commit is contained in:
@@ -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}`)
|
||||
}
|
||||
|
||||
@@ -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}`, {
|
||||
|
||||
Vendored
+1
@@ -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']
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
+61
-1
@@ -1,14 +1,22 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.ChunkUploadCompleteRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.ObjectStorageFileDTO;
|
||||
import com.xiaowang.yuminailcore.service.ChunkUploadService;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -22,10 +30,62 @@ import java.util.UUID;
|
||||
@RestController
|
||||
@RequestMapping("/admin/object-storage-file")
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class ObjectStorageFileController {
|
||||
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final MinioService minioService;
|
||||
private final ChunkUploadService chunkUploadService;
|
||||
|
||||
@PostMapping("/upload/init")
|
||||
public Result<ChunkUploadSessionVO> initChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/upload/chunk")
|
||||
public Result<Boolean> uploadChunk(HttpServletRequest request,
|
||||
@RequestParam("uploadId") String uploadId,
|
||||
@RequestParam("chunkIndex") Integer chunkIndex,
|
||||
@RequestParam("totalChunks") Integer totalChunks,
|
||||
@RequestParam("chunk") MultipartFile chunkFile) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile);
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
@PostMapping("/upload/complete")
|
||||
public Result<ObjectStorageFileVO> completeChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
|
||||
chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId());
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
String originalFilename = preparedUploadFile.getFileName();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = UUID.randomUUID() + fileExtension;
|
||||
|
||||
String fileUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
|
||||
|
||||
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
|
||||
dto.setFileName(originalFilename);
|
||||
dto.setFileUrl(fileUrl);
|
||||
dto.setStatus(1);
|
||||
|
||||
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
|
||||
chunkUploadService.clearAdminObjectStorageUpload(userId, requestDTO.getUploadId());
|
||||
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Result.error("文件上传失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/upload/{uploadId}")
|
||||
public Result<Boolean> cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId);
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
@@ -160,4 +220,4 @@ public class ObjectStorageFileController {
|
||||
List<ObjectStorageFileVO> objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status);
|
||||
return Result.success(objectStorageFileVOs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.*;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.ChunkUploadService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
|
||||
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserVO;
|
||||
@@ -20,6 +22,7 @@ import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import javax.validation.Valid;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -38,6 +41,7 @@ public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
private final MinioService minioService;
|
||||
private final ChunkUploadService chunkUploadService;
|
||||
private final VerificationCodeService verificationCodeService;
|
||||
private final UserMapper userMapper;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
@@ -381,6 +385,50 @@ public class UserController {
|
||||
* @param file 头像文件
|
||||
* @return 头像URL
|
||||
*/
|
||||
@PostMapping("/upload-avatar/init")
|
||||
public Result<ChunkUploadSessionVO> initAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(chunkUploadService.initUserAvatarUpload(userId, requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/upload-avatar/chunk")
|
||||
public Result<Boolean> uploadAvatarChunk(HttpServletRequest request,
|
||||
@RequestParam("uploadId") String uploadId,
|
||||
@RequestParam("chunkIndex") Integer chunkIndex,
|
||||
@RequestParam("totalChunks") Integer totalChunks,
|
||||
@RequestParam("chunk") MultipartFile chunkFile) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
chunkUploadService.uploadUserAvatarChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile);
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
@PostMapping("/upload-avatar/complete")
|
||||
public Result<String> completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
|
||||
chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId());
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
String originalFilename = preparedUploadFile.getFileName();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = "avatar/" + userId + "/" + UUID.randomUUID() + fileExtension;
|
||||
|
||||
String avatarUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
|
||||
userService.updateUserAvatar(userId, avatarUrl);
|
||||
chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId());
|
||||
return Result.success(avatarUrl);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Result.error("头像上传失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/upload-avatar/{uploadId}")
|
||||
public Result<Boolean> cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
chunkUploadService.clearUserAvatarUpload(userId, uploadId);
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
@PostMapping("/upload-avatar")
|
||||
public Result<String> uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
/**
|
||||
* 分片上传完成请求
|
||||
*/
|
||||
@Data
|
||||
public class ChunkUploadCompleteRequestDTO {
|
||||
|
||||
@NotBlank(message = "上传标识不能为空")
|
||||
private String uploadId;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* 分片上传初始化请求
|
||||
*/
|
||||
@Data
|
||||
public class ChunkUploadInitRequestDTO {
|
||||
|
||||
@NotBlank(message = "文件名不能为空")
|
||||
private String fileName;
|
||||
|
||||
@NotNull(message = "文件大小不能为空")
|
||||
@Min(value = 1, message = "文件大小不合法")
|
||||
private Long fileSize;
|
||||
|
||||
@NotBlank(message = "文件类型不能为空")
|
||||
private String contentType;
|
||||
|
||||
@NotBlank(message = "文件指纹不能为空")
|
||||
private String fileFingerprint;
|
||||
|
||||
@NotBlank(message = "上传场景不能为空")
|
||||
private String scene;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.xiaowang.yuminailcore.service;
|
||||
|
||||
import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO;
|
||||
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public interface ChunkUploadService {
|
||||
|
||||
ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO);
|
||||
|
||||
ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO);
|
||||
|
||||
void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile);
|
||||
|
||||
void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile);
|
||||
|
||||
PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId);
|
||||
|
||||
PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId);
|
||||
|
||||
void clearAdminObjectStorageUpload(Long ownerId, String uploadId);
|
||||
|
||||
void clearUserAvatarUpload(Long ownerId, String uploadId);
|
||||
|
||||
interface PreparedUploadFile extends AutoCloseable {
|
||||
|
||||
File getFile();
|
||||
|
||||
String getFileName();
|
||||
|
||||
String getContentType();
|
||||
|
||||
long getFileSize();
|
||||
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ public interface MinioService {
|
||||
|
||||
String uploadFile(MultipartFile file, String objectName) throws Exception;
|
||||
|
||||
String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception;
|
||||
|
||||
InputStream downloadFile(String objectName) throws Exception;
|
||||
|
||||
void deleteFile(String objectName) throws Exception;
|
||||
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO;
|
||||
import com.xiaowang.yuminailcore.service.ChunkUploadService;
|
||||
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.DigestUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChunkUploadServiceImpl implements ChunkUploadService {
|
||||
|
||||
private static final int CHUNK_SIZE = 1024 * 1024;
|
||||
private static final long SESSION_EXPIRE_HOURS = 24;
|
||||
private static final String METADATA_FILE_NAME = "metadata.json";
|
||||
private static final String CHUNK_FILE_PREFIX = "chunk-";
|
||||
private static final String CHUNK_FILE_SUFFIX = ".part";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
|
||||
return initUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, requestDTO);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
|
||||
return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) {
|
||||
uploadChunk(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) {
|
||||
uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId) {
|
||||
return prepareMergedFile(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId) {
|
||||
return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearAdminObjectStorageUpload(Long ownerId, String uploadId) {
|
||||
clearUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUserAvatarUpload(Long ownerId, String uploadId) {
|
||||
clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId);
|
||||
}
|
||||
|
||||
private ChunkUploadSessionVO initUpload(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
|
||||
validateInitRequest(ownerId, requestDTO);
|
||||
cleanupExpiredSessionsQuietly();
|
||||
|
||||
String uploadId = buildUploadId(targetType, ownerId, requestDTO);
|
||||
Path sessionDir = getSessionDir(uploadId);
|
||||
int totalChunks = (int) Math.ceil((double) requestDTO.getFileSize() / CHUNK_SIZE);
|
||||
|
||||
try {
|
||||
Files.createDirectories(sessionDir);
|
||||
|
||||
UploadMetadata metadata = readMetadataIfExists(sessionDir);
|
||||
if (metadata != null && !isCompatible(metadata, targetType, ownerId, requestDTO, totalChunks)) {
|
||||
deleteDirectory(sessionDir);
|
||||
Files.createDirectories(sessionDir);
|
||||
metadata = null;
|
||||
}
|
||||
|
||||
if (metadata == null) {
|
||||
metadata = new UploadMetadata();
|
||||
metadata.setUploadId(uploadId);
|
||||
metadata.setTargetType(targetType.name());
|
||||
metadata.setOwnerId(ownerId);
|
||||
metadata.setFileName(requestDTO.getFileName());
|
||||
metadata.setContentType(requestDTO.getContentType());
|
||||
metadata.setFileSize(requestDTO.getFileSize());
|
||||
metadata.setFileFingerprint(requestDTO.getFileFingerprint());
|
||||
metadata.setScene(requestDTO.getScene());
|
||||
metadata.setChunkSize(CHUNK_SIZE);
|
||||
metadata.setTotalChunks(totalChunks);
|
||||
metadata.setCreatedAt(Instant.now().toEpochMilli());
|
||||
}
|
||||
metadata.setUpdatedAt(Instant.now().toEpochMilli());
|
||||
writeMetadata(sessionDir, metadata);
|
||||
|
||||
ChunkUploadSessionVO sessionVO = new ChunkUploadSessionVO();
|
||||
sessionVO.setUploadId(uploadId);
|
||||
sessionVO.setChunkSize(metadata.getChunkSize());
|
||||
sessionVO.setTotalChunks(metadata.getTotalChunks());
|
||||
sessionVO.setUploadedChunks(getUploadedChunks(sessionDir, metadata.getTotalChunks()));
|
||||
return sessionVO;
|
||||
} catch (IOException e) {
|
||||
log.error("初始化分片上传失败, uploadId={}", uploadId, e);
|
||||
throw new RuntimeException("初始化上传失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadChunk(UploadTargetType targetType, Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) {
|
||||
if (ownerId == null) {
|
||||
throw new RuntimeException("未获取到上传用户信息");
|
||||
}
|
||||
if (!StringUtils.hasText(uploadId)) {
|
||||
throw new RuntimeException("上传标识不能为空");
|
||||
}
|
||||
if (chunkIndex == null || chunkIndex < 0) {
|
||||
throw new RuntimeException("分片序号不合法");
|
||||
}
|
||||
if (totalChunks == null || totalChunks <= 0) {
|
||||
throw new RuntimeException("分片总数不合法");
|
||||
}
|
||||
if (chunkFile == null || chunkFile.isEmpty()) {
|
||||
throw new RuntimeException("上传分片不能为空");
|
||||
}
|
||||
|
||||
Path sessionDir = getSessionDir(uploadId);
|
||||
UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId);
|
||||
if (!Objects.equals(metadata.getTotalChunks(), totalChunks)) {
|
||||
throw new RuntimeException("分片总数不匹配,请重新上传");
|
||||
}
|
||||
if (chunkIndex >= metadata.getTotalChunks()) {
|
||||
throw new RuntimeException("分片序号超出范围");
|
||||
}
|
||||
|
||||
try {
|
||||
Path chunkPath = getChunkPath(sessionDir, chunkIndex);
|
||||
Path tempChunkPath = sessionDir.resolve(chunkPath.getFileName().toString() + ".tmp");
|
||||
try (InputStream inputStream = chunkFile.getInputStream()) {
|
||||
Files.copy(inputStream, tempChunkPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
Files.move(tempChunkPath, chunkPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
metadata.setUpdatedAt(Instant.now().toEpochMilli());
|
||||
writeMetadata(sessionDir, metadata);
|
||||
} catch (IOException e) {
|
||||
log.error("保存分片失败, uploadId={}, chunkIndex={}", uploadId, chunkIndex, e);
|
||||
throw new RuntimeException("上传分片失败");
|
||||
}
|
||||
}
|
||||
|
||||
private PreparedUploadFile prepareMergedFile(UploadTargetType targetType, Long ownerId, String uploadId) {
|
||||
Path sessionDir = getSessionDir(uploadId);
|
||||
UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId);
|
||||
List<Integer> uploadedChunks = getUploadedChunks(sessionDir, metadata.getTotalChunks());
|
||||
if (uploadedChunks.size() != metadata.getTotalChunks()) {
|
||||
throw new RuntimeException("文件尚未上传完成,请稍后再试");
|
||||
}
|
||||
|
||||
try {
|
||||
Path mergedFilePath = Files.createTempFile("yuminail-upload-", ".tmp");
|
||||
try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergedFilePath))) {
|
||||
for (int chunkIndex = 0; chunkIndex < metadata.getTotalChunks(); chunkIndex++) {
|
||||
Path chunkPath = getChunkPath(sessionDir, chunkIndex);
|
||||
if (!Files.exists(chunkPath)) {
|
||||
throw new RuntimeException("缺少上传分片,请重新上传");
|
||||
}
|
||||
Files.copy(chunkPath, outputStream);
|
||||
}
|
||||
}
|
||||
return new LocalPreparedUploadFile(mergedFilePath.toFile(), metadata.getFileName(), metadata.getContentType(), metadata.getFileSize());
|
||||
} catch (IOException e) {
|
||||
log.error("合并上传文件失败, uploadId={}", uploadId, e);
|
||||
throw new RuntimeException("合并上传文件失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void clearUpload(UploadTargetType targetType, Long ownerId, String uploadId) {
|
||||
Path sessionDir = getSessionDir(uploadId);
|
||||
readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId);
|
||||
deleteDirectory(sessionDir);
|
||||
}
|
||||
|
||||
private UploadMetadata readAndValidateMetadata(Path sessionDir, UploadTargetType targetType, Long ownerId, String uploadId) {
|
||||
UploadMetadata metadata = readMetadataIfExists(sessionDir);
|
||||
if (metadata == null) {
|
||||
throw new RuntimeException("上传会话不存在,请重新上传");
|
||||
}
|
||||
if (!targetType.name().equals(metadata.getTargetType()) || !Objects.equals(ownerId, metadata.getOwnerId())) {
|
||||
throw new RuntimeException("无权操作该上传会话");
|
||||
}
|
||||
if (!uploadId.equals(metadata.getUploadId())) {
|
||||
throw new RuntimeException("上传会话不匹配");
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private void validateInitRequest(Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
|
||||
if (ownerId == null) {
|
||||
throw new RuntimeException("未获取到上传用户信息");
|
||||
}
|
||||
if (requestDTO == null) {
|
||||
throw new RuntimeException("上传参数不能为空");
|
||||
}
|
||||
if (!StringUtils.hasText(requestDTO.getFileName())) {
|
||||
throw new RuntimeException("文件名不能为空");
|
||||
}
|
||||
if (!StringUtils.hasText(requestDTO.getContentType())) {
|
||||
throw new RuntimeException("文件类型不能为空");
|
||||
}
|
||||
if (!StringUtils.hasText(requestDTO.getFileFingerprint())) {
|
||||
throw new RuntimeException("文件指纹不能为空");
|
||||
}
|
||||
if (!StringUtils.hasText(requestDTO.getScene())) {
|
||||
throw new RuntimeException("上传场景不能为空");
|
||||
}
|
||||
if (requestDTO.getFileSize() == null || requestDTO.getFileSize() <= 0) {
|
||||
throw new RuntimeException("文件大小不合法");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isCompatible(UploadMetadata metadata, UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO, int totalChunks) {
|
||||
return targetType.name().equals(metadata.getTargetType())
|
||||
&& Objects.equals(ownerId, metadata.getOwnerId())
|
||||
&& Objects.equals(metadata.getFileSize(), requestDTO.getFileSize())
|
||||
&& Objects.equals(metadata.getTotalChunks(), totalChunks)
|
||||
&& Objects.equals(metadata.getFileFingerprint(), requestDTO.getFileFingerprint())
|
||||
&& Objects.equals(metadata.getScene(), requestDTO.getScene());
|
||||
}
|
||||
|
||||
private String buildUploadId(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
|
||||
String raw = targetType.name() + "|" + ownerId + "|" + requestDTO.getScene() + "|" + requestDTO.getFileFingerprint();
|
||||
return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private Path getSessionDir(String uploadId) {
|
||||
return getUploadRoot().resolve(uploadId);
|
||||
}
|
||||
|
||||
private Path getUploadRoot() {
|
||||
return Path.of(System.getProperty("java.io.tmpdir"), "yuminail", "chunk-upload");
|
||||
}
|
||||
|
||||
private Path getChunkPath(Path sessionDir, int chunkIndex) {
|
||||
return sessionDir.resolve(CHUNK_FILE_PREFIX + String.format("%05d", chunkIndex) + CHUNK_FILE_SUFFIX);
|
||||
}
|
||||
|
||||
private UploadMetadata readMetadataIfExists(Path sessionDir) {
|
||||
Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME);
|
||||
if (!Files.exists(metadataPath)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(metadataPath.toFile(), UploadMetadata.class);
|
||||
} catch (IOException e) {
|
||||
log.warn("读取上传元数据失败: {}", metadataPath, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeMetadata(Path sessionDir, UploadMetadata metadata) throws IOException {
|
||||
Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME);
|
||||
objectMapper.writeValue(metadataPath.toFile(), metadata);
|
||||
}
|
||||
|
||||
private List<Integer> getUploadedChunks(Path sessionDir, int totalChunks) {
|
||||
List<Integer> uploadedChunks = new ArrayList<>();
|
||||
for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
|
||||
if (Files.exists(getChunkPath(sessionDir, chunkIndex))) {
|
||||
uploadedChunks.add(chunkIndex);
|
||||
}
|
||||
}
|
||||
return uploadedChunks;
|
||||
}
|
||||
|
||||
private void cleanupExpiredSessionsQuietly() {
|
||||
try {
|
||||
Path uploadRoot = getUploadRoot();
|
||||
if (!Files.exists(uploadRoot)) {
|
||||
return;
|
||||
}
|
||||
Instant expireAt = Instant.now().minus(SESSION_EXPIRE_HOURS, ChronoUnit.HOURS);
|
||||
try (var stream = Files.list(uploadRoot)) {
|
||||
stream.filter(Files::isDirectory)
|
||||
.sorted(Comparator.comparing(Path::toString))
|
||||
.forEach(sessionDir -> cleanupExpiredSession(sessionDir, expireAt));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("清理过期上传会话失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupExpiredSession(Path sessionDir, Instant expireAt) {
|
||||
UploadMetadata metadata = readMetadataIfExists(sessionDir);
|
||||
if (metadata == null) {
|
||||
deleteDirectory(sessionDir);
|
||||
return;
|
||||
}
|
||||
Instant updatedAt = Instant.ofEpochMilli(metadata.getUpdatedAt() == null ? 0L : metadata.getUpdatedAt());
|
||||
if (updatedAt.isBefore(expireAt)) {
|
||||
deleteDirectory(sessionDir);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteDirectory(Path directory) {
|
||||
if (directory == null || !Files.exists(directory)) {
|
||||
return;
|
||||
}
|
||||
try (var walk = Files.walk(directory)) {
|
||||
walk.sorted(Comparator.reverseOrder()).forEach(path -> {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException e) {
|
||||
log.warn("删除上传临时文件失败: {}", path, e);
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
log.warn("删除上传目录失败: {}", directory, e);
|
||||
}
|
||||
}
|
||||
|
||||
private enum UploadTargetType {
|
||||
ADMIN_OBJECT_STORAGE,
|
||||
USER_AVATAR
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class UploadMetadata {
|
||||
private String uploadId;
|
||||
private String targetType;
|
||||
private Long ownerId;
|
||||
private String fileName;
|
||||
private String contentType;
|
||||
private Long fileSize;
|
||||
private String fileFingerprint;
|
||||
private String scene;
|
||||
private Integer chunkSize;
|
||||
private Integer totalChunks;
|
||||
private Long createdAt;
|
||||
private Long updatedAt;
|
||||
}
|
||||
|
||||
private static class LocalPreparedUploadFile implements PreparedUploadFile {
|
||||
|
||||
private final File file;
|
||||
private final String fileName;
|
||||
private final String contentType;
|
||||
private final long fileSize;
|
||||
|
||||
private LocalPreparedUploadFile(File file, String fileName, String contentType, long fileSize) {
|
||||
this.file = file;
|
||||
this.fileName = fileName;
|
||||
this.contentType = contentType;
|
||||
this.fileSize = fileSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getFileSize() {
|
||||
return fileSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (file != null && file.exists() && !file.delete()) {
|
||||
log.warn("删除合并后的临时文件失败: {}", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -24,10 +24,18 @@ public class MinioServiceImpl implements MinioService {
|
||||
@Override
|
||||
public String uploadFile(MultipartFile file, String objectName) throws Exception {
|
||||
try {
|
||||
InputStream inputStream = file.getInputStream();
|
||||
long fileSize = file.getSize();
|
||||
String contentType = file.getContentType();
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
return uploadStream(inputStream, file.getSize(), file.getContentType(), objectName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("文件上传失败: {}", objectName, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception {
|
||||
try {
|
||||
minioClient.putObject(
|
||||
PutObjectArgs.builder()
|
||||
.bucket(minioConfig.getBucketName())
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.xiaowang.yuminailcore.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 分片上传会话信息
|
||||
*/
|
||||
@Data
|
||||
public class ChunkUploadSessionVO {
|
||||
|
||||
private String uploadId;
|
||||
|
||||
private Integer chunkSize;
|
||||
|
||||
private Integer totalChunks;
|
||||
|
||||
private List<Integer> uploadedChunks;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
# 2026-03-26 全站文件上传改为分片上传
|
||||
|
||||
## 本次调整
|
||||
|
||||
- 将前端现有上传入口统一改为分片上传:
|
||||
- 后台作品图片
|
||||
- 后台店铺 Banner / 店铺图片
|
||||
- 前台用户头像
|
||||
- 前端上传过程支持实时进度展示。
|
||||
- 同一用户在同一上传场景下重新选择同一文件时,会复用已有上传会话,实现断点续传。
|
||||
- 上传完成前禁止提交表单,避免保存半上传状态。
|
||||
|
||||
## 后端改动
|
||||
|
||||
- 新增分片上传请求与返回模型:
|
||||
- [ChunkUploadInitRequestDTO.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadInitRequestDTO.java)
|
||||
- [ChunkUploadCompleteRequestDTO.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadCompleteRequestDTO.java)
|
||||
- [ChunkUploadSessionVO.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ChunkUploadSessionVO.java)
|
||||
|
||||
- 新增分片上传服务:
|
||||
- [ChunkUploadService.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ChunkUploadService.java)
|
||||
- [ChunkUploadServiceImpl.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ChunkUploadServiceImpl.java)
|
||||
- 统一负责:
|
||||
- 初始化上传会话
|
||||
- 接收分片
|
||||
- 合并临时文件
|
||||
- 取消上传与临时文件清理
|
||||
- 过期分片会话清理
|
||||
- 临时分片默认落在系统临时目录下的 `java.io.tmpdir/yuminail/chunk-upload`,不会写进项目目录。
|
||||
|
||||
- 调整控制器:
|
||||
- [ObjectStorageFileController.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ObjectStorageFileController.java)
|
||||
- [UserController.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java)
|
||||
- 新增分片上传接口:
|
||||
- 初始化
|
||||
- 上传分片
|
||||
- 完成上传
|
||||
- 取消上传
|
||||
|
||||
- 调整 MinIO 上传能力:
|
||||
- [MinioService.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MinioService.java)
|
||||
- [MinioServiceImpl.java](/E:/code/xiaowang/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MinioServiceImpl.java)
|
||||
- 新增基于 `InputStream` 的上传方法,供分片合并完成后的文件复用。
|
||||
|
||||
## 前端改动
|
||||
|
||||
- 新增公共分片上传工具:
|
||||
- [chunk-upload.ts](/E:/code/xiaowang/Frontend/src/utils/chunk-upload.ts)
|
||||
- 负责:
|
||||
- 计算文件指纹
|
||||
- 初始化/续传上传会话
|
||||
- 顺序上传分片并回传整体进度
|
||||
- 取消上传时清理服务端会话
|
||||
|
||||
- 调整接口封装:
|
||||
- [admin.ts](/E:/code/xiaowang/Frontend/src/api/admin.ts)
|
||||
- [file.ts](/E:/code/xiaowang/Frontend/src/api/file.ts)
|
||||
- 新增后台文件与头像的分片上传接口封装。
|
||||
|
||||
- 调整上传页面:
|
||||
- [ProductsView.vue](/E:/code/xiaowang/Frontend/src/views/admin/ProductsView.vue)
|
||||
- [ShopsView.vue](/E:/code/xiaowang/Frontend/src/views/admin/ShopsView.vue)
|
||||
- [ProfileView.vue](/E:/code/xiaowang/Frontend/src/views/ProfileView.vue)
|
||||
- 改动点包括:
|
||||
- 接入分片上传
|
||||
- 实时显示上传进度
|
||||
- 上传中禁止提交
|
||||
- 关闭弹窗或移除文件时中断上传
|
||||
- 上传完成后仍按真实文件 ID 处理预览与删除
|
||||
|
||||
- 顺手调整:
|
||||
- [image-upload.ts](/E:/code/xiaowang/Frontend/src/utils/image-upload.ts)
|
||||
- 压缩后的文件保留原始 `lastModified`,避免影响分片续传指纹稳定性。
|
||||
|
||||
- 构建同步更新:
|
||||
- [components.d.ts](/E:/code/xiaowang/Frontend/src/components.d.ts)
|
||||
- 因头像上传区域新增 `AProgress`,自动组件类型声明同步补齐。
|
||||
|
||||
## 验证
|
||||
|
||||
- 已执行后端编译:`mvn -q -DskipTests compile`
|
||||
- 已执行前端构建:`npm run build`
|
||||
- 两端验证均通过。
|
||||
|
||||
## 数据库
|
||||
|
||||
- 本轮无 SQL 变更。
|
||||
Reference in New Issue
Block a user