存储

标准文件上传

学习如何将文件上传至Supabase存储


文件上传

标准文件上传方法适用于不超过6MB的小文件。

该方法使用传统的multipart/form-data格式,通过supabase-js SDK可以轻松实现。以下是使用标准上传方法上传文件的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// @noImplicitAny: false// ---cut---import { createClient } from '@supabase/supabase-js'// 创建Supabase客户端const supabase = createClient('your_project_url', 'your_supabase_api_key')// 使用标准上传方法上传文件async function uploadFile(file) { const { data, error } = await supabase.storage.from('bucket_name').upload('file_path', file) if (error) { // 处理错误 } else { // 处理成功 }}

覆盖文件

当上传文件到已存在的路径时,默认行为是返回 400 Asset Already Exists 错误。如果您想覆盖特定路径上的文件,可以将 upsert 选项设置为 true 或使用 x-upsert 请求头。

1
2
3
4
5
6
7
8
9
10
import { createClient } from '@supabase/supabase-js'const file = new Blob()// ---cut---// 创建 Supabase 客户端const supabase = createClient('your_project_url', 'your_supabase_api_key')await supabase.storage.from('bucket_name').upload('file_path', file, { upsert: true,})

我们建议尽量避免覆盖文件,因为我们的内容分发网络(CDN)需要一定时间将变更传播到所有边缘节点,这可能导致内容不一致。推荐的做法是上传文件到新路径,以避免传播延迟和内容不一致问题。

内容类型

默认情况下,Storage 会根据文件扩展名推断资源的内容类型。如果您想为资源指定内容类型,可以在上传时传递 contentType 选项。

1
2
3
4
5
6
7
8
9
10
import { createClient } from '@supabase/supabase-js'const file = new Blob()// ---cut---// 创建 Supabase 客户端const supabase = createClient('your_project_url', 'your_supabase_api_key')await supabase.storage.from('bucket_name').upload('file_path', file, { contentType: 'image/jpeg',})

并发控制

当两个或多个客户端同时上传文件到相同路径时:

  • 第一个完成上传的客户端会成功
  • 其他客户端将收到 400 Asset Already Exists 错误

如果您提供了 x-upsert 请求头,则最后一个完成上传的客户端会成功覆盖之前的文件。