Archiviazione di file nei bucket Supabase
Comprenda come creare e gestire bucket di storage e caricare tramite codice diversi tipi di file nel Suo progetto Supabase.
Archiviazione di file nei bucket Supabase è una lezione Supabase Backend as a Service gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Supabase Backend as a Service, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Supabase Backend as a Service include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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 anavatarsfolder 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
upsertoption.
Next, you'll dive into securing your files with Storage Policies!
Impara Supabase Backend as a Service con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 11
- Lezioni
- 40
Domande Frequenti
La lezione «Archiviazione di file nei bucket Supabase» è gratuita?
Sì — il testo completo di «Archiviazione di file nei bucket Supabase» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Supabase Backend as a Service, passa a CoddyKit PRO. Il corso Supabase Backend as a Service include 4 lezioni in totale.
Cosa imparerò in «Archiviazione di file nei bucket Supabase»?
Comprenda come creare e gestire bucket di storage e caricare tramite codice diversi tipi di file nel Suo progetto Supabase. Eserciti Supabase Backend as a Service con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Supabase Backend as a Service?
Non è richiesta alcuna esperienza precedente. Supabase Backend as a Service su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.
Quanto tempo richiede la lezione «Archiviazione di file nei bucket Supabase»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Supabase Backend as a Service?
Sì. Ogni lezione Supabase Backend as a Service include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Archiviazione di file nei bucket Supabase
- Gestione dell'accesso con le policy
- Caricamento e recupero di contenuti multimediali
- Trasformazioni delle immagini e URL firmati