utils.ts 913 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { upload } from '@/service/base'
  2. type ImageUploadParams = {
  3. file: File
  4. onProgressCallback: (progress: number) => void
  5. onSuccessCallback: (res: { id: string }) => void
  6. onErrorCallback: () => void
  7. }
  8. type ImageUpload = (v: ImageUploadParams, isPublic?: boolean, url?: string) => void
  9. export const imageUpload: ImageUpload = ({
  10. file,
  11. onProgressCallback,
  12. onSuccessCallback,
  13. onErrorCallback,
  14. }, isPublic, url) => {
  15. const formData = new FormData()
  16. formData.append('file', file)
  17. const onProgress = (e: ProgressEvent) => {
  18. if (e.lengthComputable) {
  19. const percent = Math.floor(e.loaded / e.total * 100)
  20. onProgressCallback(percent)
  21. }
  22. }
  23. upload({
  24. xhr: new XMLHttpRequest(),
  25. data: formData,
  26. onprogress: onProgress,
  27. }, isPublic, url)
  28. .then((res: { id: string }) => {
  29. onSuccessCallback(res)
  30. })
  31. .catch(() => {
  32. onErrorCallback()
  33. })
  34. }