File uploads
Let people upload avatars, photos or documents from your app. Files are protected by the same kind of security rules as your tables.
1. Create buckets
In Storage, create a bucket. A public bucket (e.g. avatars) serves files to anyone with the URL; a private one (e.g. documents) only through signed links. You can limit the file size and the allowed types (e.g. image/*).
2. Who may upload
Uploads, replacements and deletions follow policies on storage.objects. Until you add some, nobody can upload from the app. A folder per user is the usual pattern:
-- 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. Upload from your 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. Private files and signed links
// 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`]);Good to know
- Uploads count toward your plan's file storage, and downloads toward its bandwidth.
- Paths like
<user id>/avatar.pngare plain names: folders appear as you upload. - The secret key (on your server only) bypasses storage policies, like it does for tables.