73 lines
1.8 KiB
TypeScript
73 lines
1.8 KiB
TypeScript
import { root } from '@repo/core'
|
|
import { FileController } from '@repo/sdk'
|
|
import { useCallback, useState } from 'react'
|
|
|
|
import { type ApiError } from '@/lib/types'
|
|
|
|
import { handleError } from '../data/use-error'
|
|
|
|
export const useFileUpload = () => {
|
|
const [loading, setLoading] = useState(false)
|
|
const [error, setError] = useState<ApiError | null>(null)
|
|
const [progress, setProgress] = useState(0)
|
|
const [uploadedUrl, setUploadedUrl] = useState<string | null>(null)
|
|
|
|
const uploadFile = useCallback(async (file: File | Blob, folder?: string) => {
|
|
setLoading(true)
|
|
setError(null)
|
|
setProgress(0)
|
|
setUploadedUrl(null)
|
|
|
|
try {
|
|
const formData = new FormData()
|
|
formData.append('file', file as any)
|
|
if (folder) {
|
|
formData.append('folder', folder)
|
|
}
|
|
|
|
const fileController = root.get(FileController)
|
|
const { data, error } = await handleError(async () => await fileController.uploadS3(formData))
|
|
console.log({ data, error })
|
|
if (error) {
|
|
setError(error)
|
|
setLoading(false)
|
|
setProgress(0)
|
|
return { url: null, error }
|
|
}
|
|
|
|
if (data?.data) {
|
|
setUploadedUrl(data.data)
|
|
setProgress(100)
|
|
setLoading(false)
|
|
return { url: data.data, error: null }
|
|
}
|
|
|
|
setLoading(false)
|
|
setProgress(0)
|
|
return { url: null, error: { message: '上传失败' } as ApiError }
|
|
} catch (e) {
|
|
const err = e as ApiError
|
|
setError(err)
|
|
setLoading(false)
|
|
setProgress(0)
|
|
return { url: null, error: err }
|
|
}
|
|
}, [])
|
|
|
|
const reset = useCallback(() => {
|
|
setLoading(false)
|
|
setError(null)
|
|
setProgress(0)
|
|
setUploadedUrl(null)
|
|
}, [])
|
|
|
|
return {
|
|
loading,
|
|
error,
|
|
progress,
|
|
uploadedUrl,
|
|
uploadFile,
|
|
reset,
|
|
}
|
|
}
|