✨ feat(frontend): 新增上传中断并联动历史回收状态

This commit is contained in:
orion committed 2026-09-18 16:53:40 +08:00
1 parent a962f7aec7
commit e7918e9317
20 files changed
+275 -71

No files matched your search

+9 -3
View File
@@ -141,11 +141,14 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
if (response.code === 200 && response.detail) { if (response.code === 200 && response.detail) {
uploadSession.value = response.detail uploadSession.value = response.detail
options?.onSession?.(response.detail.upload_id)
options?.signal?.throwIfAborted()
return response.detail return response.detail
} else { } else {
throw new Error(response.message || '初始化上传失败') throw new Error(response.message || '初始化上传失败')
} }
} catch (error) { } catch (error) {
if (options?.signal?.aborted) throw error
handleUploadError(error) handleUploadError(error)
return null return null
} }
@@ -167,7 +170,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
const uploadSuccess = await PresignUploadService.directUploadToS3( const uploadSuccess = await PresignUploadService.directUploadToS3(
session.upload_url, session.upload_url,
file, file,
progressHandler progressHandler, options?.signal
) )
if (!uploadSuccess) { if (!uploadSuccess) {
@@ -175,11 +178,12 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
} }
// 确认上传 // 确认上传
options?.signal?.throwIfAborted()
presignStatus.value = PRESIGN_UPLOAD_STATUS.CONFIRMING presignStatus.value = PRESIGN_UPLOAD_STATUS.CONFIRMING
const confirmResponse = await PresignUploadService.confirmUpload(session.upload_id, { const confirmResponse = await PresignUploadService.confirmUpload(session.upload_id, {
expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE, expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE,
expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE
}) }, options?.signal)
if (confirmResponse.code === 200 && confirmResponse.detail?.code) { if (confirmResponse.code === 200 && confirmResponse.detail?.code) {
presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS
@@ -196,6 +200,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
throw new Error(confirmResponse.message || '确认上传失败') throw new Error(confirmResponse.message || '确认上传失败')
} }
} catch (error) { } catch (error) {
if (options?.signal?.aborted) throw error
handleUploadError(error) handleUploadError(error)
return null return null
} }
@@ -219,7 +224,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
session.upload_id, session.upload_id,
file, file,
progressHandler, progressHandler,
uploadUrl uploadUrl, options?.signal
) )
if (response.code === 200 && response.detail?.code) { if (response.code === 200 && response.detail?.code) {
@@ -237,6 +242,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
throw new Error(response.message || '代理上传失败') throw new Error(response.message || '代理上传失败')
} }
} catch (error) { } catch (error) {
if (options?.signal?.aborted) throw error
handleUploadError(error) handleUploadError(error)
return null return null
} }
+29 -3
View File
@@ -32,6 +32,9 @@ export function useSendFlow() {
const showDrawer = ref(false) const showDrawer = ref(false)
const selectedRecord = ref<SentFileRecord | null>(null) const selectedRecord = ref<SentFileRecord | null>(null)
const isSubmitting = ref(false) const isSubmitting = ref(false)
const isCancelling = ref(false)
const cleanupPending = ref(false)
const submitMessage = ref('')
const isFinalizing = ref(false) const isFinalizing = ref(false)
const fileHash = ref('') const fileHash = ref('')
const sendRecords = computed(() => fileDataStore.shareData) const sendRecords = computed(() => fileDataStore.shareData)
@@ -59,7 +62,7 @@ export function useSendFlow() {
alertStore.showAlert(message, type) alertStore.showAlert(message, type)
} }
const sentRecordActions = createSentRecordActions(notifyCopyResult) const sentRecordActions = createSentRecordActions(notifyCopyResult)
const { resetPresignUpload, submitFile, submitText } = useSendSubmit({ const { requestCancel, needsCleanup, retryCleanup, isUploadInterrupted, resetPresignUpload, submitFile, submitText } = useSendSubmit({
getMaxFileSize: () => configStore.uploadSizeLimit, getMaxFileSize: () => configStore.uploadSizeLimit,
notify: (message, type) => alertStore.showAlert(message, type), notify: (message, type) => alertStore.showAlert(message, type),
translate: t, translate: t,
@@ -211,8 +214,9 @@ export function useSendFlow() {
} }
const handleSubmit = async () => { const handleSubmit = async () => {
if (isSubmitting.value) return if (isSubmitting.value || cleanupPending.value) return
isSubmitting.value = true isSubmitting.value = true
submitMessage.value = ''
try { try {
if (sendType.value === 'file' && !selectedFile.value && selectedFiles.value.length === 0) { if (sendType.value === 'file' && !selectedFile.value && selectedFiles.value.length === 0) {
@@ -286,16 +290,37 @@ export function useSendFlow() {
throw new Error(t('send.messages.serverError')) throw new Error(t('send.messages.serverError'))
} }
} catch (error: unknown) { } catch (error: unknown) {
alertStore.showAlert(getErrorMessage(error, t('send.messages.sendFailed')), 'error') if (isUploadInterrupted(error)) {
submitMessage.value = error.cleanupPending ? '上传已中断,临时文件将在上传授权到期后自动清理' : '上传已中断,临时分片已清理,可重新发送'
} else {
cleanupPending.value = needsCleanup()
submitMessage.value = cleanupPending.value ? '传输已停止,临时文件清理未完成,请重试中断' : getErrorMessage(error, t('send.messages.sendFailed'))
alertStore.showAlert(submitMessage.value, 'error')
}
} finally { } finally {
uploadProgress.value = 0 uploadProgress.value = 0
uploadedBytes.value = 0 uploadedBytes.value = 0
totalBytes.value = 0 totalBytes.value = 0
isCancelling.value = false
isSubmitting.value = false isSubmitting.value = false
isFinalizing.value = false isFinalizing.value = false
} }
} }
const cancelUpload = async () => {
if (isCancelling.value) return
isCancelling.value = true
requestCancel()
if (isSubmitting.value) return
try {
const result = await retryCleanup()
cleanupPending.value = false
submitMessage.value = result?.detail?.completed ? `文件已上传完成,取件码:${result.detail.code}` : '上传已中断,临时分片已清理'
} catch {
submitMessage.value = '临时文件清理失败,请再次点击重试中断'
} finally { isCancelling.value = false }
}
const toggleDrawer = () => { const toggleDrawer = () => {
showDrawer.value = !showDrawer.value showDrawer.value = !showDrawer.value
} }
@@ -330,6 +355,7 @@ export function useSendFlow() {
showDrawer, showDrawer,
selectedRecord, selectedRecord,
isSubmitting, isSubmitting,
isCancelling, cleanupPending, submitMessage, cancelUpload,
isFinalizing, isFinalizing,
sendRecords, sendRecords,
uploadDescription, uploadDescription,
+36 -14
View File
@@ -1,4 +1,4 @@
import { FileService, uploadChunkedFile } from '@/services' import { FileService, PresignUploadService, uploadChunkedFile, UploadCancellation, UploadInterrupted, isUploadInterrupted } from '@/services'
import type { AlertType, ApiResponse, ExpireStyle, UploadProgress } from '@/types' import type { AlertType, ApiResponse, ExpireStyle, UploadProgress } from '@/types'
import { calculateFileHash, packFilesAsZip } from '@/utils/file-processing' import { calculateFileHash, packFilesAsZip } from '@/utils/file-processing'
import { usePresignedUpload } from './usePresignedUpload' import { usePresignedUpload } from './usePresignedUpload'
@@ -33,6 +33,10 @@ type SubmitTextOptions = {
} }
export function useSendSubmit(options: UseSendSubmitOptions) { export function useSendSubmit(options: UseSendSubmitOptions) {
let active: UploadCancellation | undefined
const requestCancel = () => active?.request()
const needsCleanup = () => Boolean(active?.signal.aborted && active.needsCleanup)
const retryCleanup = async () => active?.clean()
const { uploadFile: presignUploadFile, reset: resetPresignUpload } = usePresignedUpload({ const { uploadFile: presignUploadFile, reset: resetPresignUpload } = usePresignedUpload({
getMaxFileSize: options.getMaxFileSize, getMaxFileSize: options.getMaxFileSize,
notify: options.notify notify: options.notify
@@ -46,6 +50,7 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
return uploadChunkedFile(file, { return uploadChunkedFile(file, {
expireValue, expireValue,
expireStyle, expireStyle,
cancellation: active,
onHashCalculated: options.onHashCalculated, onHashCalculated: options.onHashCalculated,
onFinalizing: options.onFinalizing, onFinalizing: options.onFinalizing,
onProgress: (progress: UploadProgress) => { onProgress: (progress: UploadProgress) => {
@@ -67,6 +72,8 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
const code = await presignUploadFile(file, { const code = await presignUploadFile(file, {
expireValue, expireValue,
expireStyle: expireStyle as ExpireStyle, expireStyle: expireStyle as ExpireStyle,
signal: active?.signal,
onSession: (uploadId) => active?.register(() => PresignUploadService.cancelUpload(uploadId)),
onProgress: (progress) => { onProgress: (progress) => {
options.onProgress(progress) options.onProgress(progress)
} }
@@ -93,30 +100,45 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
enableChunk, enableChunk,
validateFileSize validateFileSize
}: SubmitFileOptions): Promise<ApiResponse | null> => { }: SubmitFileOptions): Promise<ApiResponse | null> => {
if (needsCleanup()) throw new Error('请先重试中断并清理上次上传')
const operation = new UploadCancellation()
active = operation
let fileToUpload = selectedFile let fileToUpload = selectedFile
try {
if (selectedFiles.length > 0) { if (selectedFiles.length > 0) {
options.notify('正在打包文件...', 'success') options.notify('正在打包文件...', 'success')
fileToUpload = await packFilesAsZip(selectedFiles) fileToUpload = await packFilesAsZip(selectedFiles)
if (!validateFileSize(fileToUpload)) { if (!validateFileSize(fileToUpload)) {
return null return null
}
options.onHashCalculated(await calculateFileHash(fileToUpload))
} }
options.onHashCalculated(await calculateFileHash(fileToUpload))
}
if (!fileToUpload) { if (!fileToUpload) {
throw new Error(options.translate('send.messages.selectFile')) throw new Error(options.translate('send.messages.selectFile'))
} }
return enableChunk operation.check()
? handleChunkUpload(fileToUpload, expireValue, expireStyle) options.onProgress({ loaded:0,total:fileToUpload.size,percentage:0 })
: handlePresignedUpload(fileToUpload, expireValue, expireStyle) const result = await (enableChunk
? handleChunkUpload(fileToUpload, expireValue, expireStyle)
: handlePresignedUpload(fileToUpload, expireValue, expireStyle))
operation.clear()
return result
} catch (error) {
if (!operation.signal.aborted || isUploadInterrupted(error)) throw error
const cleanup = await operation.clean()
if (cleanup?.detail?.completed && cleanup.detail.code) return cleanup
throw new UploadInterrupted(Boolean(cleanup?.detail?.cleanup_pending))
}
} }
const submitText = ({ text, expireValue, expireStyle }: SubmitTextOptions) => const submitText = ({ text, expireValue, expireStyle }: SubmitTextOptions) =>
FileService.uploadText(text, expireValue, expireStyle) FileService.uploadText(text, expireValue, expireStyle)
return { return {
requestCancel, needsCleanup, retryCleanup, isUploadInterrupted,
resetPresignUpload, resetPresignUpload,
submitFile, submitFile,
submitText submitText
+10 -25
View File
@@ -87,33 +87,18 @@ export class FileService {
) )
} }
static async uploadChunk( static async uploadChunk(uploadId: string, chunkIndex: number, chunk: Blob, onProgress?: (progress: UploadProgress) => void, signal?: AbortSignal): Promise<ApiResponse<ChunkUploadResponse>> {
uploadId: string, return api.post(`/chunk/upload/raw/${uploadId}/${chunkIndex}`, chunk, {
chunkIndex: number, ...multipartUploadConfig(onProgress), headers: { 'Content-Type': 'application/octet-stream' }, signal
chunk: Blob, })
onProgress?: (progress: UploadProgress) => void
): Promise<ApiResponse<ChunkUploadResponse>> {
const formData = new FormData()
formData.append('chunk', chunk)
return api.post(
`/chunk/upload/chunk/${uploadId}/${chunkIndex}`,
formData,
multipartUploadConfig(onProgress)
)
} }
static async completeChunkUpload( static async cancelChunkUpload(uploadId: string): Promise<ApiResponse<{ cancelled?: boolean; completed?: boolean; code?: string; name?: string }>> {
uploadId: string, return api.delete(`/chunk/upload/${uploadId}`)
request: ChunkUploadCompleteRequest }
): Promise<ApiResponse<FileUploadResponse>> {
return api.post( static async completeChunkUpload(uploadId: string, request: ChunkUploadCompleteRequest, signal?: AbortSignal): Promise<ApiResponse<FileUploadResponse>> {
`/chunk/upload/complete/${uploadId}`, return api.post(`/chunk/upload/complete/${uploadId}`, toUrlEncodedForm({expire_value:request.expire_value,expire_style:request.expire_style}), {...urlEncodedConfig,signal})
toUrlEncodedForm({
expire_value: request.expire_value,
expire_style: request.expire_style
}),
urlEncodedConfig
)
} }
static async selectFile(code: string): Promise<ApiResponse<ShareSelectResponse>> { static async selectFile(code: string): Promise<ApiResponse<ShareSelectResponse>> {
+2
View File
@@ -9,3 +9,5 @@ export { TrashService } from './trash'
export { uploadChunkedFile } from './upload-strategy' export { uploadChunkedFile } from './upload-strategy'
export { LocalShareService } from './local-share' export { LocalShareService } from './local-share'
export { UploadCancellation, UploadInterrupted, isUploadInterrupted } from './upload-cancellation'
+10 -7
View File
@@ -20,7 +20,8 @@ export class PresignUploadService {
uploadId: string, uploadId: string,
file: File, file: File,
onProgress?: (progress: UploadProgress) => void, onProgress?: (progress: UploadProgress) => void,
uploadUrl?: string uploadUrl?: string,
signal?: AbortSignal
): Promise<ApiResponse<PresignUploadResult>> { ): Promise<ApiResponse<PresignUploadResult>> {
const formData = new FormData() const formData = new FormData()
formData.append('file', file) formData.append('file', file)
@@ -28,31 +29,33 @@ export class PresignUploadService {
return api.put( return api.put(
uploadUrl || `/presign/upload/proxy/${uploadId}`, uploadUrl || `/presign/upload/proxy/${uploadId}`,
formData, formData,
multipartUploadConfig(onProgress) {...multipartUploadConfig(onProgress),signal}
) )
} }
static async confirmUpload( static async confirmUpload(
uploadId: string, uploadId: string,
request?: PresignConfirmRequest request?: PresignConfirmRequest,
signal?: AbortSignal
): Promise<ApiResponse<PresignUploadResult>> { ): Promise<ApiResponse<PresignUploadResult>> {
return api.post(`/presign/upload/confirm/${uploadId}`, request || {}) return api.post(`/presign/upload/confirm/${uploadId}`, request || {}, {signal})
} }
static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> { static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> {
return api.get(`/presign/upload/status/${uploadId}`) return api.get(`/presign/upload/status/${uploadId}`)
} }
static async cancelUpload(uploadId: string): Promise<ApiResponse<{ message: string }>> { static async cancelUpload(uploadId: string): Promise<ApiResponse<{ cancelled?: boolean; completed?: boolean; code?: string; name?: string; message?: string }>> {
return api.delete(`/presign/upload/${uploadId}`) return api.delete(`/presign/upload/${uploadId}`)
} }
static async directUploadToS3( static async directUploadToS3(
uploadUrl: string, uploadUrl: string,
file: File, file: File,
onProgress?: (progress: UploadProgress) => void onProgress?: (progress: UploadProgress) => void,
signal?: AbortSignal
): Promise<boolean> { ): Promise<boolean> {
await uploadToExternalUrl(uploadUrl, file, onProgress) await uploadToExternalUrl(uploadUrl, file, onProgress, signal)
return true return true
} }
} }
+26
View File
@@ -0,0 +1,26 @@
import type { ApiResponse } from '@/types'
export type CancelResult = ApiResponse<{ cancelled?: boolean; cleanup_pending?: boolean; completed?: boolean; code?: string; name?: string }>
export class UploadInterrupted extends Error {
constructor(public readonly cleanupPending = false) { super('上传已中断'); this.name = 'UploadInterrupted' }
}
export class UploadCancellation {
readonly controller = new AbortController()
private cleanup?: () => Promise<CancelResult>
private cleaning?: Promise<CancelResult | undefined>
get signal() { return this.controller.signal }
get needsCleanup() { return Boolean(this.cleanup) }
request() { this.controller.abort() }
check() { if (this.signal.aborted) throw new UploadInterrupted() }
register(cleanup: () => Promise<CancelResult>) { this.cleanup = cleanup }
clear() { this.cleanup = undefined }
async clean(): Promise<CancelResult | undefined> {
if (this.cleaning) return this.cleaning
if (!this.cleanup) return undefined
this.cleaning = this.cleanup().then(result => {
if (result.code !== 200) throw new Error('上传已停止,临时分片清理失败,请重试中断')
this.clear(); return result
}).finally(() => { this.cleaning = undefined })
return this.cleaning
}
}
export function isUploadInterrupted(error: unknown): error is UploadInterrupted { return error instanceof UploadInterrupted }
+3 -1
View File
@@ -4,9 +4,11 @@ import type { UploadProgress } from '@/types'
export async function uploadToExternalUrl( export async function uploadToExternalUrl(
uploadUrl: string, uploadUrl: string,
file: File, file: File,
onProgress?: (progress: UploadProgress) => void onProgress?: (progress: UploadProgress) => void,
signal?: AbortSignal
): Promise<void> { ): Promise<void> {
await axios.put(uploadUrl, file, { await axios.put(uploadUrl, file, {
signal,
headers: { headers: {
'Content-Type': 'application/octet-stream' 'Content-Type': 'application/octet-stream'
}, },
+3 -1
View File
@@ -5,15 +5,17 @@ export function isTransientCompletionError(error: unknown): boolean {
return !failure?.response || [408, 502, 503, 504].includes(failure.response.status || 0) return !failure?.response || [408, 502, 503, 504].includes(failure.response.status || 0)
} }
export async function waitForUploadCompletion<T>(request: () => Promise<ApiResponse<T>>, onFinalizing?: () => void): Promise<ApiResponse<T>> { export async function waitForUploadCompletion<T>(request: () => Promise<ApiResponse<T>>, onFinalizing?: () => void, signal?: AbortSignal): Promise<ApiResponse<T>> {
let announced = false, failures = 0 let announced = false, failures = 0
while (true) { while (true) {
signal?.throwIfAborted()
try { try {
const response = await request() const response = await request()
failures = 0 failures = 0
if (response.code !== 202) return response if (response.code !== 202) return response
if (!announced) { announced = true; onFinalizing?.() } if (!announced) { announced = true; onFinalizing?.() }
} catch (error) { } catch (error) {
signal?.throwIfAborted()
if (!isTransientCompletionError(error) || ++failures >= 4) throw error if (!isTransientCompletionError(error) || ++failures >= 4) throw error
} }
await new Promise(resolve => setTimeout(resolve, Math.min(1000 * (failures || 1), 3000))) await new Promise(resolve => setTimeout(resolve, Math.min(1000 * (failures || 1), 3000)))
+30 -4
View File
@@ -1,4 +1,5 @@
import { FileService } from './file' import { FileService } from './file'
import { UploadCancellation, UploadInterrupted } from './upload-cancellation'
import { waitForUploadCompletion, isTransientCompletionError } from './upload-completion' import { waitForUploadCompletion, isTransientCompletionError } from './upload-completion'
import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types' import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types'
import { calculateFileHash } from '@/utils/file-processing' import { calculateFileHash } from '@/utils/file-processing'
@@ -6,6 +7,7 @@ import { calculateFileHash } from '@/utils/file-processing'
export const CHUNK_SIZE = 100 * 1024 * 1024 export const CHUNK_SIZE = 100 * 1024 * 1024
type ChunkedUploadOptions = { type ChunkedUploadOptions = {
cancellation?: UploadCancellation
expireValue: number expireValue: number
expireStyle: string expireStyle: string
onFinalizing?: () => void onFinalizing?: () => void
@@ -31,7 +33,7 @@ async function finishUpload(file: File, options: ChunkedUploadOptions): Promise<
try { try {
const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, { const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, {
expire_value: session.expireValue, expire_style: session.expireStyle expire_value: session.expireValue, expire_style: session.expireStyle
})) }, options.cancellation?.signal), undefined, options.cancellation?.signal)
if (response.code !== 200) throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed') if (response.code !== 200) throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
pendingCompletion.delete(file) pendingCompletion.delete(file)
return response return response
@@ -48,12 +50,19 @@ const calculateCompletedBytes = (uploadedChunks: Set<number>, chunkSize: number,
return total + Math.max(0, chunkEnd - chunkStart) return total + Math.max(0, chunkEnd - chunkStart)
}, 0) }, 0)
export const uploadChunkedFile = async ( const runChunkedFile = async (
file: File, file: File,
options: ChunkedUploadOptions options: ChunkedUploadOptions
): Promise<ApiResponse<ChunkedUploadResult>> => { ): Promise<ApiResponse<ChunkedUploadResult>> => {
if (pendingCompletion.has(file)) return finishUpload(file, options) if (pendingCompletion.has(file)) {
const previous = pendingCompletion.get(file)!
options.cancellation?.register(() => FileService.cancelChunkUpload(previous.uploadId))
options.cancellation?.check()
return finishUpload(file, options)
}
options.cancellation?.check()
const fileHash = await calculateFileHash(file) const fileHash = await calculateFileHash(file)
options.cancellation?.check()
options.onHashCalculated?.(fileHash) options.onHashCalculated?.(fileHash)
const initResponse = await FileService.initChunkUpload({ const initResponse = await FileService.initChunkUpload({
@@ -77,11 +86,14 @@ export const uploadChunkedFile = async (
throw new Error(options.messages?.initFailed || 'Init chunk upload failed') throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
} }
options.cancellation?.register(() => FileService.cancelChunkUpload(uploadId))
options.cancellation?.check()
const chunkSize = initDetail.chunk_size || CHUNK_SIZE const chunkSize = initDetail.chunk_size || CHUNK_SIZE
const chunks = Math.ceil(file.size / chunkSize) const chunks = Math.ceil(file.size / chunkSize)
const uploadedChunks = new Set(initDetail.uploaded_chunks || []) const uploadedChunks = new Set(initDetail.uploaded_chunks || [])
options.onProgress?.({loaded:calculateCompletedBytes(uploadedChunks,chunkSize,file.size),total:file.size,percentage:0}) options.onProgress?.({loaded:calculateCompletedBytes(uploadedChunks,chunkSize,file.size),total:file.size,percentage:0})
for (let index = 0; index < chunks; index++) { for (let index = 0; index < chunks; index++) {
options.cancellation?.check()
if (uploadedChunks.has(index)) { if (uploadedChunks.has(index)) {
continue continue
} }
@@ -101,7 +113,7 @@ export const uploadChunkedFile = async (
total: file.size, total: file.size,
percentage: Math.min(percentage, 99) percentage: Math.min(percentage, 99)
}) })
} }, options.cancellation?.signal
) )
if (chunkResponse.code !== 200) { if (chunkResponse.code !== 200) {
@@ -113,3 +125,17 @@ export const uploadChunkedFile = async (
pendingCompletion.set(file, { uploadId, expireValue: options.expireValue, expireStyle: options.expireStyle }) pendingCompletion.set(file, { uploadId, expireValue: options.expireValue, expireStyle: options.expireStyle })
return finishUpload(file, options) return finishUpload(file, options)
} }
export async function uploadChunkedFile(file: File, options: ChunkedUploadOptions): Promise<ApiResponse<ChunkedUploadResult>> {
try {
const result = await runChunkedFile(file, options)
options.cancellation?.clear()
return result
} catch (error) {
if (!options.cancellation?.signal.aborted) throw error
pendingCompletion.delete(file)
const cancelled = await options.cancellation.clean()
if (cancelled?.detail?.completed && cancelled.detail.code) return cancelled as ApiResponse<ChunkedUploadResult>
throw new UploadInterrupted()
}
}
+8
View File
@@ -106,6 +106,14 @@ export interface AnalyticsDailyRow {
} }
export interface AnalyticsFileRow { export interface AnalyticsFileRow {
status?: 'active' | 'expired' | 'trashed' | 'purged' | 'deleted' | 'history'
is_trashed?: boolean
is_purged?: boolean
trash_reason?: string
was_restored?: boolean
can_download?: boolean
trashed_at?: string
purged_at?: string
code: string code: string
name: string name: string
size: number | string size: number | string
+2
View File
@@ -49,6 +49,8 @@ export interface PresignStatusResponse {
} }
export interface PresignUploadOptions { export interface PresignUploadOptions {
signal?: AbortSignal
onSession?: (uploadId: string) => void
expireValue?: number expireValue?: number
expireStyle?: ExpireStyle expireStyle?: ExpireStyle
onProgress?: (progress: UploadProgress) => void onProgress?: (progress: UploadProgress) => void
+10
View File
@@ -0,0 +1,10 @@
import type { AnalyticsFileRow } from '@/types'
import { getTrashReasonLabel } from './trashPresentation.ts'
export function getHistoryStatusLabel(file: AnalyticsFileRow): string {
if (file.status === 'purged' || file.is_purged) return '已清理'
if (file.status === 'trashed' || file.is_trashed) return file.trash_reason ? getTrashReasonLabel(file.trash_reason) : '回收站中'
if (file.current || file.status === 'active' || file.status === 'expired') return file.was_restored ? '现存,已从回收站恢复' : '现存'
if (file.deleted) return '已删除'
return '历史'
}
+6 -5
View File
@@ -19,11 +19,7 @@ export function formatTrashTime(value?: string | null, now?: number): string {
} }
export function getTrashPresentation(item: TrashFileItem, now: number) { export function getTrashPresentation(item: TrashFileItem, now: number) {
const reasons: Record<string, string> = { const reason = getTrashReasonLabel(item.trashReason)
manual: '手动删除', batch_delete: '批量删除', expired_time: '保存到期',
expired_count: '次数用尽', expired_both: '到期且次数用尽', expired: '历史自动回收'
}
const reason = item.trashReason ? reasons[item.trashReason] || '其他原因' : '未记录'
if (item.isTrashPurged) return { if (item.isTrashPurged) return {
state: '已清理', tone: 'muted', reason, reminder: '', state: '已清理', tone: 'muted', reason, reminder: '',
@@ -45,3 +41,8 @@ export function getTrashPresentation(item: TrashFileItem, now: number) {
note: valid && remainingMs <= 0 ? '已到清理时间,等待后台处理。' : '' note: valid && remainingMs <= 0 ? '已到清理时间,等待后台处理。' : ''
} }
} }
export function getTrashReasonLabel(reason?: string | null): string {
const labels: Record<string,string> = {manual:'手动删除',batch_delete:'批量删除',expired_time:'保存到期',expired_count:'次数用尽',expired_both:'到期且次数用尽',expired:'历史自动回收'}
return reason ? labels[reason] || '其他原因' : '未记录'
}
+10 -2
View File
@@ -14,10 +14,12 @@
<div class="p-5 sm:p-8"> <div class="p-5 sm:p-8">
<PageHeader :title="config.name" @title-click="toRetrieve" /> <PageHeader :title="config.name" @title-click="toRetrieve" />
<form @submit.prevent="handleSubmit" class="space-y-5 sm:space-y-8"> <form @submit.prevent="handleSubmit" class="space-y-5 sm:space-y-8">
<fieldset :disabled="isSubmitting || cleanupPending">
<SendTypeSelector <SendTypeSelector
:selected-type="sendType" :selected-type="sendType"
@update:selected-type="sendType = $event" @update:selected-type="sendType = $event"
/> />
</fieldset>
<transition name="fade" mode="out-in"> <transition name="fade" mode="out-in">
<div v-if="sendType === 'file'" key="file" class="grid grid-cols-1 gap-8"> <div v-if="sendType === 'file'" key="file" class="grid grid-cols-1 gap-8">
@@ -28,7 +30,7 @@
:progress="uploadProgress" :progress="uploadProgress"
:uploaded-bytes="uploadedBytes" :uploaded-bytes="uploadedBytes"
:total-bytes="totalBytes" :total-bytes="totalBytes"
:disabled="isSubmitting" :disabled="isSubmitting || cleanupPending"
:upload-status="isFinalizing ? 'confirming' : isSubmitting ? 'uploading' : 'idle'" :upload-status="isFinalizing ? 'confirming' : isSubmitting ? 'uploading' : 'idle'"
:description="uploadDescription" :description="uploadDescription"
@file-selected="handleFileSelected" @file-selected="handleFileSelected"
@@ -44,15 +46,17 @@
/> />
</div> </div>
</transition> </transition>
<fieldset :disabled="isSubmitting || cleanupPending">
<ExpirationSelector <ExpirationSelector
v-model:expiration-method="expirationMethod" v-model:expiration-method="expirationMethod"
v-model:expiration-value="expirationValue" v-model:expiration-value="expirationValue"
:options="expirationOptions" :options="expirationOptions"
/> />
</fieldset>
<!-- 提交按钮 --> <!-- 提交按钮 -->
<button <button
type="submit" type="submit"
:disabled="isSubmitting" :disabled="isSubmitting || cleanupPending"
class="fcb-action fcb-button-primary w-full bg-[#7198a6] text-white font-bold shadow-[0_10px_20px_rgba(113,152,166,.24)] py-4 px-6 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 transition-all duration-300 transform hover:shadow-lg relative overflow-hidden group disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none disabled:hover:scale-100" class="fcb-action fcb-button-primary w-full bg-[#7198a6] text-white font-bold shadow-[0_10px_20px_rgba(113,152,166,.24)] py-4 px-6 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 transition-all duration-300 transform hover:shadow-lg relative overflow-hidden group disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none disabled:hover:scale-100"
> >
<span class="relative z-10 flex items-center justify-center text-sm sm:text-lg"> <span class="relative z-10 flex items-center justify-center text-sm sm:text-lg">
@@ -81,6 +85,9 @@
<span>{{ isSubmitting ? t('send.submitting') : t('send.submit') }}</span> <span>{{ isSubmitting ? t('send.submitting') : t('send.submit') }}</span>
</span> </span>
</button> </button>
<button v-if="(isSubmitting && sendType === 'file') || cleanupPending" type="button" class="fcb-action fcb-button-danger min-h-11 w-full rounded-xl px-4 py-3 font-semibold disabled:opacity-60" :disabled="isCancelling" @click="cancelUpload">{{ isCancelling ? '正在中断并清理…' : cleanupPending ? '重试中断并清理' : '中断上传' }}</button>
<p v-if="isCancelling" role="status" class="text-center text-sm opacity-75">正在停止传输并清理临时文件,请稍候。</p>
<p v-else-if="submitMessage" role="status" class="text-center text-sm">{{ submitMessage }}</p>
</form> </form>
<div class="mt-6 text-center"> <div class="mt-6 text-center">
<router-link to="/" class="fcb-action inline-flex min-h-11 items-center rounded-lg px-2 text-sm text-[#3f6a77] transition duration-200 hover:bg-[#dcebed] hover:text-[#315c69] dark:text-[#b8d4dc] dark:hover:bg-[#333d49] sm:px-3 sm:text-base"> <router-link to="/" class="fcb-action inline-flex min-h-11 items-center rounded-lg px-2 text-sm text-[#3f6a77] transition duration-200 hover:bg-[#dcebed] hover:text-[#315c69] dark:text-[#b8d4dc] dark:hover:bg-[#333d49] sm:px-3 sm:text-base">
@@ -168,6 +175,7 @@ const {
showDrawer, showDrawer,
selectedRecord, selectedRecord,
isSubmitting, isSubmitting,
isCancelling, cleanupPending, submitMessage, cancelUpload,
isFinalizing, isFinalizing,
sendRecords, sendRecords,
uploadDescription, uploadDescription,
+1 -6
View File
@@ -1704,6 +1704,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { getHistoryStatusLabel } from '@/utils/history-status'
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from 'vue' import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
@@ -2057,12 +2058,6 @@ const handleHistoryPageSizeChange = (size: number) => {
const formatHistoryBytes = (value: number | string | undefined) => const formatHistoryBytes = (value: number | string | undefined) =>
formatFileSize(Number(value || 0), 1) formatFileSize(Number(value || 0), 1)
const formatHistoryDate = (value?: string) => (value ? formatTimestamp(value) : '-') const formatHistoryDate = (value?: string) => (value ? formatTimestamp(value) : '-')
const getHistoryStatusLabel = (file: AnalyticsFileRow) => {
if (file.deleted) return '已删除'
if (file.expired) return '已过期'
if (file.current) return '现存'
return '历史'
}
const primaryTextClass = computed(() => (isDarkMode.value ? 'text-white' : 'text-gray-900')) const primaryTextClass = computed(() => (isDarkMode.value ? 'text-white' : 'text-gray-900'))
const mutedTextClass = computed(() => (isDarkMode.value ? 'text-gray-400' : 'text-gray-500')) const mutedTextClass = computed(() => (isDarkMode.value ? 'text-gray-400' : 'text-gray-500'))
+8
View File
@@ -75,3 +75,11 @@ Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http`
`uploadCompletion.test.mjs` 覆盖 202 轮询、临时网络错误重试及明确失败退出; `uploadCompletion.test.mjs` 覆盖 202 轮询、临时网络错误重试及明确失败退出;
`uploadStrategy.integration.test.mjs` 验证用户在丢失完成响应后手动重试时复用原上传 ID, `uploadStrategy.integration.test.mjs` 验证用户在丢失完成响应后手动重试时复用原上传 ID,
不重新上传分片。发送页在此阶段显示文件校验提示,确认成功后才给出取件码。 不重新上传分片。发送页在此阶段显示文件校验提示,确认成功后才给出取件码。
## 中断上传与历史状态
`uploadCancellation.integration.test.mjs` 验证中断当前请求、等待初始化返回会话后清理、
清理失败后重试及同文件重新上传。`cancelUpload.browser.mjs` 使用隔离 API 数据验证
发送页“中断上传”按钮和清理反馈,不会访问线上文件。
`historyStatus.test.mjs` 验证回收站原因共用标签、已清理、恢复后的现存状态。
分片使用原始请求体发送,最大 100 MiB,避免 multipart 额外开销超过 CDN 上限。
+18
View File
@@ -0,0 +1,18 @@
import assert from 'node:assert/strict'
export async function runCancelUploadCheck(page, base='http://127.0.0.1:5180/theme-assets/') {
let cleanup=0,completes=0,requests=0,startedResolve
const started=new Promise(resolve=>startedResolve=resolve)
await page.route('**/api/v1/config',r=>r.fulfill({json:{code:200,detail:{config:{name:'test',expireStyle:['day'],max_save_seconds:0,openUpload:1,enableChunk:1,uploadSize:1073741824}}}}))
await page.route('**/chunk/upload/init/**',r=>r.fulfill({json:{code:200,detail:{upload_id:'isolated-cancel',chunk_size:1048576,uploaded_chunks:[]}}}))
await page.route('**/chunk/upload/raw/**',async r=>{requests++;startedResolve();await new Promise(resolve=>setTimeout(resolve,1500));try{await r.fulfill({json:{code:200}})}catch{}})
await page.route('**/chunk/upload/complete/**',r=>{completes++;return r.fulfill({json:{code:200,detail:{code:'UNEXPECTED'}}})})
await page.route('**/chunk/upload/isolated-cancel',r=>{assert.equal(r.request().method(),'DELETE');cleanup++;return r.fulfill({json:{code:200,detail:{cancelled:true}}})})
await page.goto(base+'#/send')
await page.locator('input[type=file]').setInputFiles({name:'cancel.txt',mimeType:'text/plain',buffer:Buffer.alloc(3*1024*1024,97)})
await page.locator('button[type=submit]').click();await started
await page.getByRole('button',{name:'中断上传',exact:true}).click()
await page.getByText('上传已中断,临时分片已清理,可重新发送',{exact:true}).waitFor()
assert.equal(cleanup,1);assert.equal(requests,1);assert.equal(completes,0)
assert.equal(await page.locator('button[type=submit]').isEnabled(),true)
console.log('browser cancellation: stopped raw request, cleaned once, no subsequent chunks/publication')
}
+13
View File
@@ -0,0 +1,13 @@
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {getHistoryStatusLabel} from '../src/utils/history-status.ts'
test('history labels follow trash and purge before expiry/current flags',()=>{
for(const [value,want] of [[{current:true},'现存'],[{status:'trashed',current:false,expired:true},'回收站中'],[{status:'purged',deleted:true},'已清理'],[{status:'active',current:true},'现存'],[{status:'expired',current:true},'现存'],[{deleted:true,current:false},'已删除'],[{current:false},'历史']])assert.equal(getHistoryStatusLabel(value),want)
})
test('restored history is distinct and recoverable reasons match trash labels',()=>{
assert.equal(getHistoryStatusLabel({status:'active',current:true,was_restored:true}),'现存,已从回收站恢复')
assert.equal(getHistoryStatusLabel({status:'trashed',trash_reason:'expired_count'}),'次数用尽')
assert.equal(getHistoryStatusLabel({status:'trashed',trash_reason:'expired_time'}),'保存到期')
assert.equal(getHistoryStatusLabel({status:'trashed',trash_reason:'manual'}),'手动删除')
})
@@ -0,0 +1,41 @@
import {test,before,after} from 'node:test'
import assert from 'node:assert/strict'
import {createServer} from 'vite'
let server,upload,service,Control
before(async()=>{
server=await createServer({server:{middlewareMode:true,watch:null,hmr:false},optimizeDeps:{noDiscovery:true,include:[]},appType:'custom'})
service=(await server.ssrLoadModule('/src/services/file.ts')).FileService
upload=(await server.ssrLoadModule('/src/services/upload-strategy.ts')).uploadChunkedFile
Control=(await server.ssrLoadModule('/src/services/upload-cancellation.ts')).UploadCancellation
globalThis.window={isSecureContext:true}
})
after(async()=>{await server?.close();delete globalThis.window})
test('cancel during chunk stops later chunks, waits for cleanup and does not publish',async()=>{
const original={init:service.initChunkUpload,chunk:service.uploadChunk,complete:service.completeChunkUpload,cancel:service.cancelChunkUpload};const control=new Control();let chunks=0,cleanup=0,completes=0
service.initChunkUpload=async()=>({code:200,detail:{upload_id:'cancel-id',chunk_size:4,uploaded_chunks:[]}})
service.uploadChunk=async(id,i,chunk,progress,signal)=>{chunks++;control.request();throw new DOMException('Aborted','AbortError')}
service.cancelChunkUpload=async id=>{assert.equal(id,'cancel-id');cleanup++;return {code:200,detail:{cancelled:true}}}
service.completeChunkUpload=async()=>{completes++;return {code:200}}
try{await assert.rejects(upload(new File(['abcdefghijkl'],'a.txt'),{expireValue:1,expireStyle:'day',cancellation:control}),/上传已中断/);assert.equal(chunks,1);assert.equal(cleanup,1);assert.equal(completes,0)}finally{Object.assign(service,{initChunkUpload:original.init,uploadChunk:original.chunk,completeChunkUpload:original.complete,cancelChunkUpload:original.cancel})}
})
test('cancel while initialization is pending cleans the returned id rather than leaking session',async()=>{
const original={init:service.initChunkUpload,cancel:service.cancelChunkUpload};const control=new Control();let cleaned=false
service.initChunkUpload=async()=>{control.request();return {code:200,detail:{upload_id:'late-id',chunk_size:4}}}
service.cancelChunkUpload=async id=>{cleaned=id==='late-id';return {code:200,detail:{cancelled:true}}}
try{await assert.rejects(upload(new File(['abcd'],'b.txt'),{expireValue:1,expireStyle:'day',cancellation:control}),/上传已中断/);assert.ok(cleaned)}finally{service.initChunkUpload=original.init;service.cancelChunkUpload=original.cancel}
})
test('failed cancellation cleanup is retryable and next submission initializes a new session',async()=>{
const original={init:service.initChunkUpload,chunk:service.uploadChunk,complete:service.completeChunkUpload,cancel:service.cancelChunkUpload}
const control=new Control();let inits=0,cancelCalls=0,completeCalls=0
service.initChunkUpload=async()=>({code:200,detail:{upload_id:'id-'+(++inits),chunk_size:4,uploaded_chunks:[]}})
service.uploadChunk=async()=>({code:200})
service.completeChunkUpload=async()=>{completeCalls++;if(completeCalls===1){control.request();throw new Error('aborted')}return {code:200,detail:{code:'NEWCODE1'}}}
service.cancelChunkUpload=async()=>{cancelCalls++;if(cancelCalls===1)throw new Error('cleanup unavailable');return {code:200,detail:{cancelled:true}}}
const file=new File(['abcd'],'retry.txt')
try{
await assert.rejects(upload(file,{expireValue:1,expireStyle:'day',cancellation:control}),/cleanup unavailable/)
assert.equal(control.needsCleanup,true);await control.clean();assert.equal(control.needsCleanup,false)
const done=await upload(file,{expireValue:1,expireStyle:'day',cancellation:new Control()})
assert.equal(done.detail.code,'NEWCODE1');assert.equal(inits,2)
}finally{Object.assign(service,{initChunkUpload:original.init,uploadChunk:original.chunk,completeChunkUpload:original.complete,cancelChunkUpload:original.cancel})}
})