fx-1 / src /services /imageUpload.ts
felix-fx's picture
Initial commit from GitHub fx-1
6711fd5 verified
Raw History Blame Contribute Delete
1.49 kB
/**
* خدمة رفع الصور باستخدام Supabase Storage
*/
import { supabase } from '@/integrations/supabase/client';
export async function uploadImageToExternal(file: File, bucket = 'avatars'): Promise<string> {
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error('يجب تسجيل الدخول أولاً');
const fileExt = file.name.split('.').pop() || 'jpg';
const fileName = `${user.id}/${Date.now()}.${fileExt}`;
const { data, error } = await supabase.storage
.from(bucket)
.upload(fileName, file, {
cacheControl: '3600',
upsert: true,
});
if (error) throw error;
const { data: urlData } = supabase.storage
.from(bucket)
.getPublicUrl(data.path);
return urlData.publicUrl;
}
export async function uploadImageFromUrl(url: string): Promise<string> {
try {
const response = await fetch(url);
const blob = await response.blob();
const file = new File([blob], 'image.jpg', { type: 'image/jpeg' });
return await uploadImageToExternal(file);
} catch (error) {
console.error('Error uploading image from URL:', error);
return url;
}
}
export async function validateImageFile(file: File): Promise<boolean> {
// التحقق من نوع الملف
if (!file.type.startsWith('image/')) {
return false;
}
// التحقق من حجم الملف (أقل من 5 ميجابايت)
if (file.size > 5 * 1024 * 1024) {
return false;
}
return true;
}