fileUtils.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { RawFile } from '../types';
  2. export const readFile = (file: File): Promise<RawFile> => {
  3. return new Promise((resolve, reject) => {
  4. const reader = new FileReader();
  5. reader.onload = () => {
  6. const base64String = reader.result as string;
  7. // Remove data URL prefix (e.g., "data:image/png;base64,") to get raw base64
  8. const base64Content = base64String.split(',')[1];
  9. resolve({
  10. name: file.name,
  11. type: file.type,
  12. size: file.size,
  13. content: base64Content,
  14. preview: file.type.startsWith('image/') ? base64String : undefined,
  15. file: file,
  16. });
  17. };
  18. reader.onerror = () => {
  19. // Rejection returns the file name to allow the UI to construct a localized message
  20. reject(file.name);
  21. };
  22. // Read as Data URL to easily get Base64
  23. reader.readAsDataURL(file);
  24. });
  25. };
  26. export const formatBytes = (bytes: number, decimals = 2) => {
  27. if (!+bytes) return '0 B';
  28. const k = 1024;
  29. const dm = decimals < 0 ? 0 : decimals;
  30. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  31. const i = Math.floor(Math.log(bytes) / Math.log(k));
  32. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
  33. };