Upload images, track progress, get download URLs, and write security rules.
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage';
const storage = getStorage();
async function uploadImage(file, path) {
const storageRef = ref(storage, path);
const uploadTask = uploadBytesResumable(storageRef, file);
return new Promise((resolve, reject) => {
uploadTask.on(
'state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log(`Upload ${progress.toFixed(0)}%`);
},
reject,
async () => {
const url = await getDownloadURL(uploadTask.snapshot.ref);
resolve(url);
}
);
});
}
// Usage
const url = await uploadImage(file, `users/${user.uid}/avatar.jpg`);
await updateDoc(doc(db, 'users', user.uid), { avatarUrl: url });rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
// Users can read/write their own files
match /users/{userId}/{allPaths=**} {
allow read: if request.auth != null;
allow write: if request.auth.uid == userId;
}
// Public images readable by all
match /public/{allPaths=**} {
allow read: if true;
allow write: if request.auth != null;
}
}
}ref(storage, path) → uploadBytesResumable(ref, file) → getDownloadURL().uploadBytesResumable over uploadBytes to track upload progress.{userId} to match the authenticated user's folder.