Files
JayuCloud/FD-Frontend/src/utils/chunk-upload.ts
T
2026-06-15 15:53:55 +08:00

202 lines
7.8 KiB
TypeScript

import type { AxiosProgressEvent } from 'axios'
/**
* Purpose: ChunkUploadSession supports chunk-upload.ts by holding or executing the chunk upload session page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadSession {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
/**
* Purpose: ChunkUploadInitRequest supports chunk-upload.ts by holding or executing the chunk upload init request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
/**
* Purpose: ChunkUploadApi supports chunk-upload.ts by holding or executing the chunk upload api page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
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>
}
/**
* Purpose: ChunkUploadOptions supports chunk-upload.ts by holding or executing the chunk upload options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadOptions<TResponse> {
file: File
scene: string
api: ChunkUploadApi<TResponse>
preprocessFile?: (file: File) => Promise<File>
onProgress?: (percent: number) => void
}
/**
* Purpose: ChunkUploadResult supports chunk-upload.ts by holding or executing the chunk upload result page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadResult<TResponse> {
response: TResponse
uploadId: string
processedFile: File
}
/**
* Purpose: ChunkUploadTask supports chunk-upload.ts by holding or executing the chunk upload task page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadTask<TResponse> {
promise: Promise<ChunkUploadResult<TResponse>>
cancel: () => void
getUploadId: () => string
}
/**
* Purpose: computeFileFingerprint supports chunk-upload.ts by holding or executing the compute file fingerprint page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
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('')
}
/**
* Purpose: getChunkSizeByIndex supports chunk-upload.ts by holding or executing the get chunk size by index page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
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)
}
/**
* Purpose: calculateUploadedBytes supports chunk-upload.ts by holding or executing the calculate uploaded bytes page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => {
return uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
}
/**
* Purpose: createChunkUploadTask supports chunk-upload.ts by holding or executing the create chunk upload task page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
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
}
}