refactor: modularize frontend flows
This commit is contained in:
1 parent
9300607f96
commit
a11e7900b4
85 files changed
+4654
-4363
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import api from './client'
|
||||
import type { AdminUser, ApiResponse } from '@/types'
|
||||
|
||||
export class AuthService {
|
||||
static async login(password: string): Promise<ApiResponse<AdminUser>> {
|
||||
return api.post('/admin/login', { password })
|
||||
}
|
||||
|
||||
static async logout(): Promise<ApiResponse> {
|
||||
return api.post('/admin/logout')
|
||||
}
|
||||
|
||||
static async verifyToken(): Promise<ApiResponse<AdminUser>> {
|
||||
return api.get('/admin/verify')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { API_STATUS_CODES, TIME_CONSTANTS } from '@/constants'
|
||||
import type { ApiErrorPayload } from '@/types'
|
||||
import { clearStoredToken, readStoredToken } from '@/utils/auth-storage'
|
||||
|
||||
export const AUTH_EVENTS = {
|
||||
UNAUTHORIZED: 'filecodebox:auth:unauthorized'
|
||||
} as const
|
||||
|
||||
const rawBaseURL =
|
||||
import.meta.env.MODE === 'production'
|
||||
? import.meta.env.VITE_API_BASE_URL_PROD
|
||||
: import.meta.env.VITE_API_BASE_URL_DEV
|
||||
|
||||
export const apiBaseURL = typeof rawBaseURL === 'string' ? rawBaseURL.replace(/\/+$/, '') : ''
|
||||
|
||||
const clientOptions = {
|
||||
baseURL: apiBaseURL,
|
||||
timeout: TIME_CONSTANTS.REQUEST_TIMEOUT,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}
|
||||
|
||||
const apiClient = axios.create(clientOptions)
|
||||
export const rawApiClient = axios.create(clientOptions)
|
||||
|
||||
const attachAuthToken = (config: InternalAxiosRequestConfig) => {
|
||||
const token = readStoredToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const handleAuthError = (error: AxiosError<ApiErrorPayload>) => {
|
||||
if (error.response?.status === API_STATUS_CODES.UNAUTHORIZED) {
|
||||
clearStoredToken()
|
||||
window.dispatchEvent(new CustomEvent(AUTH_EVENTS.UNAUTHORIZED))
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
apiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
rawApiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response.data,
|
||||
handleAuthError
|
||||
)
|
||||
|
||||
rawApiClient.interceptors.response.use((response) => response, handleAuthError)
|
||||
|
||||
export default apiClient
|
||||
@@ -0,0 +1,16 @@
|
||||
import api from './client'
|
||||
import type { ApiResponse, ConfigState } from '@/types'
|
||||
|
||||
export class ConfigService {
|
||||
static async getConfig(): Promise<ApiResponse<ConfigState>> {
|
||||
return api.get('/admin/config/get')
|
||||
}
|
||||
|
||||
static async getUserConfig(): Promise<ApiResponse<ConfigState>> {
|
||||
return api.post('/')
|
||||
}
|
||||
|
||||
static async updateConfig(config: Partial<ConfigState>): Promise<ApiResponse> {
|
||||
return api.patch('/admin/config/update', config)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import api, { rawApiClient } from './client'
|
||||
import { multipartUploadConfig } from './shared'
|
||||
import type {
|
||||
ApiResponse,
|
||||
ChunkUploadCompleteRequest,
|
||||
ChunkUploadInitRequest,
|
||||
ChunkUploadInitResponse,
|
||||
ChunkUploadResponse,
|
||||
FileEditForm,
|
||||
FileInfo,
|
||||
FileListResponse,
|
||||
FileUploadResponse,
|
||||
ShareSelectResponse,
|
||||
TextSendResponse,
|
||||
UploadProgress
|
||||
} from '@/types'
|
||||
|
||||
const urlEncodedConfig = {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
}
|
||||
}
|
||||
|
||||
const toUrlEncodedForm = (data: Record<string, string | number>) => {
|
||||
const form = new URLSearchParams()
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
form.append(key, String(value))
|
||||
})
|
||||
return form
|
||||
}
|
||||
|
||||
export class FileService {
|
||||
static async uploadFile(
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<FileUploadResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.post('/share/file/', formData, multipartUploadConfig(onProgress))
|
||||
}
|
||||
|
||||
static async uploadText(
|
||||
text: string,
|
||||
expireValue = 1,
|
||||
expireStyle = 'day'
|
||||
): Promise<ApiResponse<TextSendResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('text', text)
|
||||
formData.append('expire_value', String(expireValue))
|
||||
formData.append('expire_style', expireStyle)
|
||||
return api.post('/share/text/', formData, multipartUploadConfig())
|
||||
}
|
||||
|
||||
static async initChunkUpload(
|
||||
request: ChunkUploadInitRequest
|
||||
): Promise<ApiResponse<ChunkUploadInitResponse>> {
|
||||
return api.post(
|
||||
'/chunk/upload/init/',
|
||||
toUrlEncodedForm({
|
||||
file_name: request.file_name,
|
||||
file_size: request.file_size,
|
||||
chunk_size: request.chunk_size,
|
||||
file_hash: request.file_hash
|
||||
}),
|
||||
urlEncodedConfig
|
||||
)
|
||||
}
|
||||
|
||||
static async uploadChunk(
|
||||
uploadId: string,
|
||||
chunkIndex: number,
|
||||
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(
|
||||
uploadId: string,
|
||||
request: ChunkUploadCompleteRequest
|
||||
): Promise<ApiResponse<FileUploadResponse>> {
|
||||
return api.post(
|
||||
`/chunk/upload/complete/${uploadId}`,
|
||||
toUrlEncodedForm({
|
||||
expire_value: request.expire_value,
|
||||
expire_style: request.expire_style
|
||||
}),
|
||||
urlEncodedConfig
|
||||
)
|
||||
}
|
||||
|
||||
static async selectFile(code: string): Promise<ApiResponse<ShareSelectResponse>> {
|
||||
return api.post('/share/select/', { code })
|
||||
}
|
||||
|
||||
static async getFile(code: string): Promise<ApiResponse<FileInfo>> {
|
||||
return api.get(`/file/${code}`)
|
||||
}
|
||||
|
||||
static async downloadFile(code: string): Promise<Blob> {
|
||||
const response = await rawApiClient.get<Blob>(`/download/${code}`, {
|
||||
responseType: 'blob'
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
static async getAdminFileList(params: {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
}): Promise<ApiResponse<FileListResponse>> {
|
||||
return api.get('/admin/file/list', { params })
|
||||
}
|
||||
|
||||
static async updateFile(data: FileEditForm): Promise<ApiResponse> {
|
||||
return api.patch('/admin/file/update', data)
|
||||
}
|
||||
|
||||
static async deleteAdminFile(id: number): Promise<ApiResponse> {
|
||||
return api.delete('/admin/file/delete', {
|
||||
data: { id }
|
||||
})
|
||||
}
|
||||
|
||||
static async downloadAdminFile(
|
||||
id: number
|
||||
): Promise<{ data: Blob; headers: Record<string, string> }> {
|
||||
const response = await rawApiClient.get<Blob>('/admin/file/download', {
|
||||
params: { id },
|
||||
responseType: 'blob'
|
||||
})
|
||||
return {
|
||||
data: response.data,
|
||||
headers: response.headers as Record<string, string>
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-266
@@ -1,266 +1,7 @@
|
||||
// API 服务层
|
||||
import api from '@/utils/api'
|
||||
import axios from 'axios'
|
||||
import type {
|
||||
ApiResponse,
|
||||
FileInfo,
|
||||
ConfigState,
|
||||
AdminUser,
|
||||
FileUploadResponse,
|
||||
TextSendResponse,
|
||||
DashboardData,
|
||||
FileListResponse,
|
||||
FileEditForm
|
||||
} from '@/types'
|
||||
import type {
|
||||
UploadProgress,
|
||||
PresignInitRequest,
|
||||
PresignInitResponse,
|
||||
PresignConfirmRequest,
|
||||
PresignUploadResult,
|
||||
PresignStatusResponse
|
||||
} from '@/types'
|
||||
|
||||
// 系统配置服务
|
||||
export class ConfigService {
|
||||
static async getConfig(): Promise<ApiResponse<ConfigState>> {
|
||||
return api.get('/admin/config/get')
|
||||
}
|
||||
static async getUserConfig(): Promise<ApiResponse<ConfigState>> {
|
||||
return api.post('/')
|
||||
}
|
||||
static async updateConfig(config: Partial<ConfigState>): Promise<ApiResponse> {
|
||||
return api.patch('/admin/config/update', config)
|
||||
}
|
||||
}
|
||||
|
||||
// 文件服务
|
||||
export class FileService {
|
||||
static async uploadFile(
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<FileUploadResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.post('/share/file/', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
timeout: 0, // 禁用超时限制
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (onProgress && progressEvent.total) {
|
||||
const progress: UploadProgress = {
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
}
|
||||
onProgress(progress)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
static async uploadText(text: string): Promise<ApiResponse<TextSendResponse>> {
|
||||
return api.post('/share/text/', { content: text })
|
||||
}
|
||||
|
||||
static async getFile(code: string): Promise<ApiResponse<FileInfo>> {
|
||||
return api.get(`/file/${code}`)
|
||||
}
|
||||
|
||||
static async downloadFile(code: string): Promise<Blob> {
|
||||
const response = await api.get(`/download/${code}`, {
|
||||
responseType: 'blob'
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
static async deleteFile(fileId: string): Promise<ApiResponse> {
|
||||
return api.post('/admin/file/delete', { id: fileId })
|
||||
}
|
||||
|
||||
static async getFileList(
|
||||
page = 1,
|
||||
limit = 10
|
||||
): Promise<
|
||||
ApiResponse<{
|
||||
files: FileInfo[]
|
||||
total: number
|
||||
page: number
|
||||
limit: number
|
||||
}>
|
||||
> {
|
||||
return api.get('/admin/file/list', {
|
||||
params: { page, size: limit }
|
||||
})
|
||||
}
|
||||
|
||||
// 文件管理相关方法
|
||||
static async getAdminFileList(params: {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
}): Promise<ApiResponse<FileListResponse>> {
|
||||
return api.get('/admin/file/list', { params })
|
||||
}
|
||||
|
||||
static async updateFile(data: FileEditForm): Promise<ApiResponse> {
|
||||
return api.patch('/admin/file/update', data)
|
||||
}
|
||||
|
||||
static async deleteAdminFile(id: number): Promise<ApiResponse> {
|
||||
return api.delete('/admin/file/delete', {
|
||||
data: { id }
|
||||
})
|
||||
}
|
||||
|
||||
static async downloadAdminFile(
|
||||
id: number
|
||||
): Promise<{ data: Blob; headers: Record<string, string> }> {
|
||||
return api.get('/admin/file/download', {
|
||||
params: { id },
|
||||
responseType: 'blob'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 认证服务
|
||||
export class AuthService {
|
||||
static async login(password: string): Promise<ApiResponse<AdminUser>> {
|
||||
return api.post('/admin/login', { password })
|
||||
}
|
||||
|
||||
static async logout(): Promise<ApiResponse> {
|
||||
return api.post('/admin/logout')
|
||||
}
|
||||
|
||||
static async verifyToken(): Promise<ApiResponse<AdminUser>> {
|
||||
return api.get('/admin/verify')
|
||||
}
|
||||
}
|
||||
|
||||
// 统计服务
|
||||
export class StatsService {
|
||||
static async getDashboardStats(): Promise<
|
||||
ApiResponse<{
|
||||
totalFiles: number
|
||||
totalDownloads: number
|
||||
todayUploads: number
|
||||
todayDownloads: number
|
||||
storageUsed: number
|
||||
recentFiles: FileInfo[]
|
||||
}>
|
||||
> {
|
||||
return api.get('/admin/dashboard')
|
||||
}
|
||||
|
||||
static async getDashboard(): Promise<ApiResponse<DashboardData>> {
|
||||
return api.get('/admin/dashboard')
|
||||
}
|
||||
}
|
||||
|
||||
// 预签名上传服务
|
||||
export class PresignUploadService {
|
||||
/**
|
||||
* 初始化上传会话
|
||||
*/
|
||||
static async initUpload(request: PresignInitRequest): Promise<ApiResponse<PresignInitResponse>> {
|
||||
return api.post('/presign/upload/init', request)
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理模式上传
|
||||
*/
|
||||
static async proxyUpload(
|
||||
uploadId: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.put(`/presign/upload/proxy/${uploadId}`, formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (onProgress && progressEvent.total) {
|
||||
const progress: UploadProgress = {
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
}
|
||||
onProgress(progress)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认直传上传
|
||||
*/
|
||||
static async confirmUpload(
|
||||
uploadId: string,
|
||||
request?: PresignConfirmRequest
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
return api.post(`/presign/upload/confirm/${uploadId}`, request || {})
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询上传状态
|
||||
*/
|
||||
static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> {
|
||||
return api.get(`/presign/upload/status/${uploadId}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消上传
|
||||
*/
|
||||
static async cancelUpload(uploadId: string): Promise<ApiResponse<{ message: string }>> {
|
||||
return api.delete(`/presign/upload/${uploadId}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* S3 直传(不经过后端)
|
||||
*/
|
||||
static async directUploadToS3(
|
||||
uploadUrl: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await axios.put(uploadUrl, file, {
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (onProgress && progressEvent.total) {
|
||||
const progress: UploadProgress = {
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
}
|
||||
onProgress(progress)
|
||||
}
|
||||
}
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 导出所有服务
|
||||
export const services = {
|
||||
config: ConfigService,
|
||||
file: FileService,
|
||||
auth: AuthService,
|
||||
stats: StatsService,
|
||||
presignUpload: PresignUploadService
|
||||
}
|
||||
|
||||
export default services
|
||||
export { AUTH_EVENTS } from './client'
|
||||
export { AuthService } from './auth'
|
||||
export { ConfigService } from './config'
|
||||
export { FileService } from './file'
|
||||
export { PresignUploadService } from './presign-upload'
|
||||
export { StatsService } from './stats'
|
||||
export { uploadChunkedFile } from './upload-strategy'
|
||||
@@ -0,0 +1,53 @@
|
||||
import api from './client'
|
||||
import { multipartUploadConfig } from './shared'
|
||||
import { uploadToExternalUrl } from './upload-client'
|
||||
import type {
|
||||
ApiResponse,
|
||||
PresignConfirmRequest,
|
||||
PresignInitRequest,
|
||||
PresignInitResponse,
|
||||
PresignStatusResponse,
|
||||
PresignUploadResult,
|
||||
UploadProgress
|
||||
} from '@/types'
|
||||
|
||||
export class PresignUploadService {
|
||||
static async initUpload(request: PresignInitRequest): Promise<ApiResponse<PresignInitResponse>> {
|
||||
return api.post('/presign/upload/init', request)
|
||||
}
|
||||
|
||||
static async proxyUpload(
|
||||
uploadId: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.put(`/presign/upload/proxy/${uploadId}`, formData, multipartUploadConfig(onProgress))
|
||||
}
|
||||
|
||||
static async confirmUpload(
|
||||
uploadId: string,
|
||||
request?: PresignConfirmRequest
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
return api.post(`/presign/upload/confirm/${uploadId}`, request || {})
|
||||
}
|
||||
|
||||
static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> {
|
||||
return api.get(`/presign/upload/status/${uploadId}`)
|
||||
}
|
||||
|
||||
static async cancelUpload(uploadId: string): Promise<ApiResponse<{ message: string }>> {
|
||||
return api.delete(`/presign/upload/${uploadId}`)
|
||||
}
|
||||
|
||||
static async directUploadToS3(
|
||||
uploadUrl: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<boolean> {
|
||||
await uploadToExternalUrl(uploadUrl, file, onProgress)
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { AxiosRequestConfig } from 'axios'
|
||||
import type { UploadProgress } from '@/types'
|
||||
|
||||
export const multipartUploadConfig = (
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): AxiosRequestConfig => ({
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (onProgress && progressEvent.total) {
|
||||
onProgress({
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import api from './client'
|
||||
import type { ApiResponse, DashboardData } from '@/types'
|
||||
|
||||
export class StatsService {
|
||||
static async getDashboard(): Promise<ApiResponse<DashboardData>> {
|
||||
return api.get('/admin/dashboard')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import axios from 'axios'
|
||||
import type { UploadProgress } from '@/types'
|
||||
|
||||
export async function uploadToExternalUrl(
|
||||
uploadUrl: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<void> {
|
||||
await axios.put(uploadUrl, file, {
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (!onProgress || !progressEvent.total) {
|
||||
return
|
||||
}
|
||||
|
||||
onProgress({
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { FileService } from './file'
|
||||
import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types'
|
||||
import { calculateFileHash } from '@/utils/file-processing'
|
||||
|
||||
const CHUNK_SIZE = 5 * 1024 * 1024
|
||||
|
||||
type ChunkedUploadOptions = {
|
||||
expireValue: number
|
||||
expireStyle: string
|
||||
onHashCalculated?: (hash: string) => void
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
messages?: {
|
||||
initFailed?: string
|
||||
chunkFailed?: (index: number) => string
|
||||
completeFailed?: string
|
||||
}
|
||||
}
|
||||
|
||||
type ChunkedUploadResult = ChunkUploadInitResponse | FileUploadResponse
|
||||
|
||||
const calculateCompletedBytes = (uploadedChunks: Set<number>, chunkSize: number, fileSize: number) =>
|
||||
Array.from(uploadedChunks).reduce((total, index) => {
|
||||
const chunkStart = index * chunkSize
|
||||
const chunkEnd = Math.min((index + 1) * chunkSize, fileSize)
|
||||
return total + Math.max(0, chunkEnd - chunkStart)
|
||||
}, 0)
|
||||
|
||||
export const uploadChunkedFile = async (
|
||||
file: File,
|
||||
options: ChunkedUploadOptions
|
||||
): Promise<ApiResponse<ChunkedUploadResult>> => {
|
||||
const fileHash = await calculateFileHash(file)
|
||||
options.onHashCalculated?.(fileHash)
|
||||
|
||||
const chunks = Math.ceil(file.size / CHUNK_SIZE)
|
||||
const initResponse = await FileService.initChunkUpload({
|
||||
file_name: file.name,
|
||||
file_size: file.size,
|
||||
chunk_size: CHUNK_SIZE,
|
||||
file_hash: fileHash
|
||||
})
|
||||
|
||||
if (initResponse.code !== 200) {
|
||||
throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
|
||||
}
|
||||
|
||||
if (initResponse.detail?.existed) {
|
||||
return initResponse
|
||||
}
|
||||
|
||||
const initDetail = initResponse.detail
|
||||
const uploadId = initDetail?.upload_id
|
||||
if (!uploadId) {
|
||||
throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
|
||||
}
|
||||
|
||||
const uploadedChunks = new Set(initDetail.uploaded_chunks || [])
|
||||
for (let index = 0; index < chunks; index++) {
|
||||
if (uploadedChunks.has(index)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const start = index * CHUNK_SIZE
|
||||
const end = Math.min(start + CHUNK_SIZE, file.size)
|
||||
const chunk = file.slice(start, end)
|
||||
const chunkResponse = await FileService.uploadChunk(
|
||||
uploadId,
|
||||
index,
|
||||
new Blob([chunk], { type: file.type }),
|
||||
(progress) => {
|
||||
const completedBytes = calculateCompletedBytes(uploadedChunks, CHUNK_SIZE, file.size)
|
||||
const percentage = Math.round(((completedBytes + progress.loaded) * 100) / file.size)
|
||||
options.onProgress?.({
|
||||
loaded: completedBytes + progress.loaded,
|
||||
total: file.size,
|
||||
percentage: Math.min(percentage, 99)
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
if (chunkResponse.code !== 200) {
|
||||
throw new Error(options.messages?.chunkFailed?.(index) || `Chunk upload failed: ${index}`)
|
||||
}
|
||||
uploadedChunks.add(index)
|
||||
}
|
||||
|
||||
const completeResponse = await FileService.completeChunkUpload(uploadId, {
|
||||
expire_value: options.expireValue,
|
||||
expire_style: options.expireStyle
|
||||
})
|
||||
|
||||
if (completeResponse.code !== 200) {
|
||||
throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
|
||||
}
|
||||
|
||||
return completeResponse
|
||||
}
|
||||
Reference in new issue
Block a user