0Pricing
Supabase Backend as a Service · Aula

Armazenamento de arquivos em buckets do Supabase

Entenda como criar e gerenciar buckets de armazenamento e enviar programaticamente vários tipos de arquivo para seu projeto no Supabase.

Armazenamento de arquivos em buckets do Supabase é uma aula grátis de Supabase Backend as a Service no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Supabase Backend as a Service, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Supabase Backend as a Service inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Welcome to Supabase Storage

Managing files like images, videos, and documents is crucial for many apps. Supabase offers a robust, S3-compatible object storage solution right out of the box!

It's designed for scalability and security, letting you store and serve user-generated content or application assets with ease.

Understanding Storage Buckets

Think of a bucket as a top-level folder or container for your files. Each Supabase project can have multiple buckets.

  • Organize files by type (e.g., avatars, product-images).
  • Set different security rules for each bucket.
  • Buckets are isolated, meaning files in one bucket don't mix with another.

Create a Bucket in the Dashboard

You can create buckets directly from the Supabase Dashboard. Navigate to the Storage section and click "New bucket".

Give it a unique name and decide if it should be public or private. We'll explore these options next!

Public or Private Access?

This is a key decision when creating a bucket:

  • Public Buckets: Anyone with the URL can access files. Great for static assets like profile pictures or public documents.
  • Private Buckets: Files require authentication and specific policies to be accessed. Ideal for sensitive user data or premium content.

You can change this setting later, but it's good to plan ahead!

Setting Up for Uploads (JS)

To upload files from your app, you'll use the Supabase client library. First, ensure you have your Supabase URL and anon key initialized.

We'll use a simple JavaScript example. Imagine supabase is your initialized client.

import { createClient } from '@supabase/supabase-js';

const SUPABASE_URL = 'YOUR_SUPABASE_URL';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';

const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

console.log('Supabase client initialized.');

Programmatically Upload a File

The storage.from().upload() method is your go-to for uploading. It needs the bucket name, the path within the bucket, and the file itself.

Let's simulate uploading a simple text file. In a real app, you'd get the file from an HTML <input type="file">.

import { createClient } from '@supabase/supabase-js';

const SUPABASE_URL = 'YOUR_SUPABASE_URL';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';

const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

async function uploadFile() {
  // In a real app, 'file' would come from an input element
  const mockFile = new File(['Hello CoddyKit!'], 'hello.txt', {
    type: 'text/plain',
  });

  const { data, error } = await supabase.storage
    .from('my-first-bucket') // Replace with your bucket name
    .upload('public/hello_world.txt', mockFile);

  if (error) {
    console.error('Upload error:', error.message);
  } else {
    console.log('Upload successful:', data);
  }
}

uploadFile();

File Paths & Overwrite Behavior

The 'path' in .upload('path/to/file.txt', file) determines where your file lands within the bucket.

  • 'my-image.jpg': Uploads to the bucket's root.
  • 'avatars/user123.png': Creates an avatars folder if it doesn't exist.

By default, uploading to an existing path will overwrite the old file. You can control this with the upsert option.

Controlling Overwrites with Upsert

The upsert option in the upload method lets you decide what happens if a file with the same path already exists.

  • upsert: true (default): Overwrites the existing file.
  • upsert: false: Returns an error if a file with the same path exists, preventing accidental overwrites.

Use upsert: false when you want to ensure unique file names.

import { createClient } from '@supabase/supabase-js';

const SUPABASE_URL = 'YOUR_SUPABASE_URL';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';

const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

async function uploadUniqueFile() {
  const mockFile = new File(['Unique content!'], 'unique.txt', {
    type: 'text/plain',
  });

  // This will fail if 'public/unique.txt' already exists
  const { data, error } = await supabase.storage
    .from('my-first-bucket') // Replace with your bucket name
    .upload('public/unique.txt', mockFile, { upsert: false });

  if (error) {
    console.error('Upload failed (file exists or other error):', error.message);
  } else {
    console.log('Unique upload successful:', data);
  }
}

uploadUniqueFile();

Handles All Your File Needs

Supabase Storage isn't limited to just images or text files. It can handle any file type you throw at it!

  • Images: PNG, JPG, GIF, SVG
  • Videos: MP4, MOV, WebM
  • Documents: PDF, DOCX, XLSX
  • Audio: MP3, WAV

Just ensure your client-side code provides the correct file object.

Quick Check on Buckets

You've learned about Supabase Storage buckets and how to upload files. Let's test your understanding!

Recap: Storing Files

Great job! You've learned the fundamentals of Supabase Storage:

  • What buckets are and how to create them.
  • The difference between public and private buckets.
  • How to programmatically upload files using the Supabase client.
  • Controlling file overwrites with the upsert option.

Next, you'll dive into securing your files with Storage Policies!

Perguntas Frequentes

A aula “Armazenamento de arquivos em buckets do Supabase” é grátis?

Sim — o texto completo de “Armazenamento de arquivos em buckets do Supabase” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Supabase Backend as a Service, atualize para CoddyKit PRO. O curso de Supabase Backend as a Service inclui 4 aulas no total.

O que vou aprender em “Armazenamento de arquivos em buckets do Supabase”?

Entenda como criar e gerenciar buckets de armazenamento e enviar programaticamente vários tipos de arquivo para seu projeto no Supabase. Você pratica Supabase Backend as a Service com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Supabase Backend as a Service?

Nenhuma experiência prévia é necessária. Supabase Backend as a Service no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Armazenamento de arquivos em buckets do Supabase”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Supabase Backend as a Service?

Sim. Cada aula de Supabase Backend as a Service inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Armazenamento de arquivos em buckets do Supabase
  2. Gerenciamento de acesso com políticas
  3. Envio e recuperação de arquivos de mídia
  4. Transformações de Imagens e URLs Assinadas
← Voltar para Supabase Backend as a Service