Caricamento file
Permetti alle persone di caricare avatar, foto o documenti dalla tua app. I file sono protetti dallo stesso tipo di regole di sicurezza delle tue tabelle.
1. Crea i bucket
In Archiviazione, crea un bucket. Un bucket pubblico (ad es. avatars) serve i file a chiunque abbia l'URL; uno privato (ad es. documents) solo tramite link firmati. Puoi limitare la dimensione dei file e i tipi consentiti (ad es. image/*).
2. Chi può caricare
Caricamenti, sostituzioni ed eliminazioni seguono le policy su storage.objects. Finché non ne aggiungi qualcuna, nessuno può caricare file dall'app. Una cartella per utente è lo schema più comune:
-- Signed-in users may upload, replace and delete files only in their own folder: <user id>/… create policy "Upload to own folder" on storage.objects for insert with check (bucket_id = 'avatars' and (storage.foldername(name))[1] = espobase.user_id()::text); create policy "Replace own files" on storage.objects for update using (bucket_id = 'avatars' and (storage.foldername(name))[1] = espobase.user_id()::text) with check (bucket_id = 'avatars' and (storage.foldername(name))[1] = espobase.user_id()::text); create policy "Delete own files" on storage.objects for delete using (bucket_id = 'avatars' and (storage.foldername(name))[1] = espobase.user_id()::text); -- For a private bucket, also allow reading your own files: create policy "Read own files" on storage.objects for select using (bucket_id = 'documents' and (storage.foldername(name))[1] = espobase.user_id()::text);
3. Carica dalla tua app
const { data: me } = await espobase.auth.getUser();
const path = `${me!.user.id}/avatar.png`;
// Upload (upsert replaces an existing file at the same path).
const { error } = await espobase.storage.from("avatars").upload(path, file, { upsert: true });
// Public bucket: a permanent URL anyone can open.
const { publicUrl } = espobase.storage.from("avatars").getPublicUrl(path);4. File privati e link firmati
// Private bucket: a link that works for 10 minutes, created by someone allowed to read the file.
const { data } = await espobase.storage.from("documents").createSignedUrl(`${userId}/contract.pdf`, 600);
window.open(data!.signedUrl);
// List and delete
const { data: files } = await espobase.storage.from("documents").list(`${userId}/`);
await espobase.storage.from("documents").remove([`${userId}/old.pdf`]);Buono a sapersi
- I caricamenti contano per l'archiviazione file del tuo piano, e i download per la sua banda.
- Percorsi come
<user id>/avatar.pngsono semplici nomi: le cartelle compaiono man mano che carichi. - La chiave segreta (solo sul tuo server) ignora le policy di archiviazione, come fa per le tabelle.