Now that you've set up your Supabase project and are familiar with the basics of Supabase Storage, let's dive into the exciting part: uploading files! Supabase makes file uploads straightforward, whether you're working with a web application, a mobile app, or even server-side scripts. We'll cover how to upload files using the Supabase JavaScript client library, which is a common scenario for web development.
Before we start uploading, ensure you have your Supabase client initialized in your application. If you haven't done this yet, refer back to the introductory chapters of this book.
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseKey = 'YOUR_SUPABASE_ANON_KEY'
const supabase = createClient(supabaseUrl, supabaseKey)The core function for uploading files in Supabase is upload on the storage client. This function requires a few key pieces of information:
- Path: The full path within your storage bucket where you want to store the file. This includes the filename.
- File: The actual file content you want to upload. This can be a
Fileobject (from an HTML input element), aBlob, or anArrayBuffer. - Options (optional): This object can include configurations like
contentType(useful for browsers to correctly interpret the file type) andupsert(to overwrite existing files if a file with the same path already exists).
Let's look at a common scenario: uploading a file selected by a user via an HTML file input.
const fileInput = document.getElementById('myFileInput');
const file = fileInput.files[0]; // Get the first selected file
async function uploadFile() {
const filePath = `public/${file.name}`;
const { data, error } = await supabase.storage
.from('my-bucket-name') // Replace with your actual bucket name
.upload(filePath, file, {
contentType: file.type,
upsert: true // Optional: overwrite if file exists
});
if (error) {
console.error('Error uploading file:', error);
} else {
console.log('File uploaded successfully:', data);
// You can now use the 'data.path' or 'data.Key' to reference the uploaded file
}
}
fileInput.addEventListener('change', uploadFile);