Uploading Files
To upload a file, you build a Storage reference and use uploadBytes. Splitting the file path by user ID makes things much easier to manage later on.
Code Example
javascript
import { getStorage, ref, uploadBytes } from 'firebase/storage';
import { getAuth } from 'firebase/auth';
const storage = getStorage();
const auth = getAuth();
async function uploadAvatar(file) {
const user = auth.currentUser;
if (!user) throw new Error('Login required');
const filePath = 'avatars/' + user.uid + '/' + file.name;
const fileRef = ref(storage, filePath);
await uploadBytes(fileRef, file);
console.log('Avatar uploaded:', filePath);
}What does this code do?
avatars/userId/fileName and uploads the file into Storage under that path. Since the user ID is baked in, you can cleanly separate each user's own files.
Common mistake
If the file.name a user uploads happens to match an existing one, it can overwrite it. In production, append a timestamp or random ID so every filename stays unique.