Skip to content
Storage

从存储中提供资源

Serving assets from Storage

公共存储桶 #

🌐 Public buckets

正如在 Buckets Fundamentals 中提到的,上传到公共存储桶的所有文件都是公开可访问的,并且可以享受较高的 CDN 缓存命中率。

🌐 As mentioned in the Buckets Fundamentals all files uploaded in a public bucket are publicly accessible and benefit a high CDN cache HIT ratio.

你可以通过使用这个常规网址来访问它们:

🌐 You can access them by using this conventional URL:

1
https://[project_id].supabase.co/storage/v1/object/public/[bucket]/[asset-name]

你也可以使用 Supabase SDK getPublicUrl 来帮你生成这个 URL

🌐 You can also use the Supabase SDK getPublicUrl to generate this URL for you

1
import { createClient } from '@supabase/supabase-js'
2
const supabase = createClient('your_project_url', 'your_supabase_api_key')
3
4
// ---cut---
5
const { data } = supabase.storage.from('bucket').getPublicUrl('filePath.jpg')
6
7
console.log(data.publicUrl)

正在下载 #

🌐 Downloading

如果你希望浏览器自动下载这个资源而不是尝试直接打开它,你可以添加 ?download 查询字符串参数。

🌐 If you want the browser to start an automatic download of the asset instead of trying serving it, you can add the ?download query string parameter.

默认情况下,它会使用资源名称将文件保存到磁盘上。你也可以选择通过 download 参数传入自定义名称,如下所示:?download=customname.jpg

🌐 By default it will use the asset name to save the file on disk. You can optionally pass a custom name to the download parameter as following: ?download=customname.jpg

带查询参数的程序化下载 #

🌐 Programmatic downloads with query parameters

在使用 SDK 的 download() 方法时,你可以传入额外的查询参数来定制下载行为:

🌐 When using the SDK's download() method, you can pass additional query parameters to customize the download behavior:

1
import { createClient } from '@supabase/supabase-js'
2
const supabase = createClient('your_project_url', 'your_supabase_api_key')
3
4
// ---cut---
5
// Download with custom filename
6
const { data, error } = await supabase.storage.from('avatars').download('avatar1.png', {
7
download: 'my-custom-name.png',
8
})

私有存储桶 #

🌐 Private buckets

存储在非公开存储桶中的资源被视为私有的,不能像公共存储桶那样通过公共 URL 访问。

🌐 Assets stored in a non-public bucket are considered private and are not accessible via a public URL like the public buckets.

你只能通过以下方式访问它们:

🌐 You can access them only by:

  • 在服务器上为 URL 签署一个限时链接,例如使用 Edge Functions。
  • 使用 GET 请求 URL https://[project_id].supabase.co/storage/v1/object/authenticated/[bucket]/[asset-name] 和用户授权头

签署网址 #

🌐 Signing URLs

你可以通过调用 SDK 上的 createSignedUrl 方法来签署一个限时 URL,然后分享给你的用户。

1
import { createClient } from '@supabase/supabase-js'
2
const supabase = createClient('your_project_url', 'your_supabase_api_key')
3
4
// ---cut---
5
const { data, error } = await supabase.storage
6
.from('bucket')
7
.createSignedUrl('private-document.pdf', 3600)
8
9
if (data) {
10
console.log(data.signedUrl)
11
}