Skip to content

建立 2026-09-14 更新 2026-09-14

Storage

Storage 用來放圖片、文件、影片。檔案活在 bucket(桶)裡,中繼資料存在 Postgres,所以權限一樣用 RLS,不是另一套密碼。

Bucket

在 Dashboard → Storage 新增 bucket,例如 avatars

  • Public bucket:任何人有 URL 就能下載。適合公開頭像、行銷圖。
  • Private bucket:下載要過政策,或改用有時效的 signed URL。適合使用者文件。

路徑習慣:{user_id}/filename.png,政策才能用資料夾名稱對 auth.uid()

上傳與讀取

const file = event.target.files[0]
const path = `${user.id}/${file.name}`

const { data, error } = await supabase.storage
  .from('avatars')
  .upload(path, file, { upsert: false })

標準上傳適合小檔(官方建議大於約 6MB 改用 resumable / TUS)。同路徑重複上傳預設會失敗;要覆蓋才設 upsert: true。覆蓋後 CDN 可能短暫拿到舊檔,能換路徑就換路徑。

公開檔:

const { data } = supabase.storage.from('avatars').getPublicUrl(path)

私有檔用有時效的連結:

const { data, error } = await supabase.storage
  .from('avatars')
  .createSignedUrl(path, 60 * 60) // 秒

沒有政策就傳不上去

storage.objects 寫政策,否則 upload 會失敗。例如:已登入使用者只能管理自己資料夾裡的檔:

create policy "Users can upload own avatars"
on storage.objects for insert
to authenticated
with check (
  bucket_id = 'avatars'
  and (select auth.uid())::text = (storage.foldername(name))[1]
);

公開讀取再加 for select。細節與更多範例見官方 Storage Quickstart

相關資料