63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
/**
|
|
* File: upload.ts
|
|
* Created by: AI Assistant
|
|
* Date: 2025-11-29
|
|
* Purpose: Client-side file upload utility functions
|
|
* Part of: kreatiVortex - Platform Pembelajaran Tari Online
|
|
*/
|
|
|
|
export interface UploadedFile {
|
|
id: string;
|
|
name: string;
|
|
originalName: string;
|
|
mimeType: string;
|
|
size: number;
|
|
url: string;
|
|
}
|
|
|
|
export async function uploadFile(file: File, folder: string = 'uploads'): Promise<UploadedFile> {
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
formData.append('folder', folder);
|
|
|
|
const response = await fetch('/api/upload', {
|
|
method: 'POST',
|
|
body: formData,
|
|
credentials: 'include',
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to upload file');
|
|
}
|
|
|
|
const result = await response.json();
|
|
|
|
if (!result.success) {
|
|
throw new Error(result.message || 'Upload failed');
|
|
}
|
|
|
|
return result.data;
|
|
}
|
|
|
|
export function isAllowedFileType(file: File): boolean {
|
|
const allowedTypes = [
|
|
'application/pdf',
|
|
'application/msword',
|
|
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
'image/jpeg',
|
|
'image/png',
|
|
'image/gif'
|
|
];
|
|
|
|
return allowedTypes.includes(file.type);
|
|
}
|
|
|
|
export function formatFileSize(bytes: number): string {
|
|
if (bytes === 0) return '0 Bytes';
|
|
|
|
const k = 1024;
|
|
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
|
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
|
} |