| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- import { RawFile } from '../types';
- export const readFile = (file: File): Promise<RawFile> => {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () => {
- const base64String = reader.result as string;
- // Remove data URL prefix (e.g., "data:image/png;base64,") to get raw base64
- const base64Content = base64String.split(',')[1];
- resolve({
- name: file.name,
- type: file.type,
- size: file.size,
- content: base64Content,
- preview: file.type.startsWith('image/') ? base64String : undefined,
- file: file,
- });
- };
- reader.onerror = () => {
- // Rejection returns the file name to allow the UI to construct a localized message
- reject(file.name);
- };
- // Read as Data URL to easily get Base64
- reader.readAsDataURL(file);
- });
- };
- export const formatBytes = (bytes: number, decimals = 2) => {
- if (!+bytes) return '0 B';
- const k = 1024;
- const dm = decimals < 0 ? 0 : decimals;
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
- };
|