Storage
Common use cases
Core
Initialization
import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";
// Set the configuration for your app
// TODO: Replace with your app's config object
const firebaseConfig = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket-url>'
};
const firebaseApp = initializeApp(firebaseConfig);
// Get a reference to the storage service, which is used to create references in your storage bucket
const storage = getStorage(firebaseApp);
Upload a file
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
const storage = getStorage();
const imageRef = ref(storage, 'images/' + file.name);
uploadBytesResumable(imageRef, file, metadata)
.then((snapshot) => {
console.log('Uploaded', snapshot.totalBytes, 'bytes.');
console.log('File metadata:', snapshot.metadata);
// Let's get a download URL for the file.
getDownloadURL(snapshot.ref).then((url) => {
console.log('File available at', url);
// ...
});
}).catch((error) => {
console.error('Upload failed', error);
// ...
});
Delete a file
import { getStorage, ref, deleteObject } from "firebase/storage";
const storage = getStorage();
// Create a reference to the file to delete
const desertRef = ref(storage, 'images/desert.jpg');
// Delete the file
deleteObject(desertRef).then(() => {
// File deleted successfully
}).catch((error) => {
// Uh-oh, an error occurred!
});
References
Create a reference
import { getStorage, ref } from "firebase/storage";
// Get a reference to the storage service, which is used to create references in your storage bucket
const storage = getStorage();
// Create a storage reference from our storage service
const storageRef = ref(storage);
Create a child reference
import { getStorage, ref } from "firebase/storage";
const storage = getStorage();
// Create a child reference
const imagesRef = ref(storage, 'images');
// imagesRef now points to 'images'
// Child references can also take paths delimited by '/'
const spaceRef = ref(storage, 'images/space.jpg');
// spaceRef now points to "images/space.jpg"
// imagesRef still points to "images"
Navigate to the a parent reference
import { getStorage, ref } from "firebase/storage";
const storage = getStorage();
const spaceRef = ref(storage, 'images/space.jpg');
// Parent allows us to move to the parent of a reference
const imagesRef = spaceRef.parent;
// imagesRef now points to 'images'
// Root allows us to move all the way back to the top of our bucket
const rootRef = spaceRef.root;
// rootRef now points to the root
Reference properties
import { getStorage, ref } from "firebase/storage";
const storage = getStorage();
const spaceRef = ref(storage, 'images/space.jpg');
// Reference's path is: 'images/space.jpg'
// This is analogous to a file path on disk
spaceRef.fullPath;
// Reference's name is the last segment of the full path: 'space.jpg'
// This is analogous to the file name
spaceRef.name;
// Reference's bucket is the name of the storage bucket where files are stored
spaceRef.bucket;
Upload files
Manage uploads
import { getStorage, ref, uploadBytesResumable } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'images/mountains.jpg');
// Upload the file and metadata
const uploadTask = uploadBytesResumable(storageRef, file);
// Pause the upload
uploadTask.pause();
// Resume the upload
uploadTask.resume();
// Cancel the upload
uploadTask.cancel();
Monitor uploads
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'images/rivers.jpg');
const uploadTask = uploadBytesResumable(storageRef, file);
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed',
(snapshot) => {
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
// Handle unsuccessful uploads
},
() => {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
});
}
);
Upload a blob
import { getStorage, ref, uploadBytes } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'some-child');
// 'file' comes from the Blob or File API
uploadBytes(storageRef, file).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
Upload a byte array
import { getStorage, ref, uploadBytes } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'some-child');
const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]);
uploadBytes(storageRef, bytes).then((snapshot) => {
console.log('Uploaded an array!');
});
Upload metadata
import { getStorage, ref, uploadBytes } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'images/mountains.jpg');
// Create file metadata including the content type
/** @type {any} */
const metadata = {
contentType: 'image/jpeg',
};
// Upload the file and metadata
const uploadTask = uploadBytes(storageRef, file, metadata);
Upload a string
import { getStorage, ref, uploadString } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'some-child');
// Raw string is the default if no format is provided
const message = 'This is my message.';
uploadString(storageRef, message).then((snapshot) => {
console.log('Uploaded a raw string!');
});
// Base64 formatted string
const message2 = '5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';
uploadString(storageRef, message2, 'base64').then((snapshot) => {
console.log('Uploaded a base64 string!');
});
// Base64url formatted string
const message3 = '5b6p5Y-344GX44G-44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';
uploadString(storageRef, message3, 'base64url').then((snapshot) => {
console.log('Uploaded a base64url string!');
});
// Data URL string
const message4 = 'data:text/plain;base64,5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';
uploadString(storageRef, message4, 'data_url').then((snapshot) => {
console.log('Uploaded a data_url string!');
});
Handle upload errors
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
const storage = getStorage();
// Create the file metadata
/** @type {any} */
const metadata = {
contentType: 'image/jpeg'
};
// Upload file and metadata to the object 'images/mountains.jpg'
const storageRef = ref(storage, 'images/' + file.name);
const uploadTask = uploadBytesResumable(storageRef, file, metadata);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on('state_changed',
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
// ...
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
},
() => {
// Upload completed successfully, now we can get the download URL
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
});
}
);
Download files
Get a download URL
import { getStorage, ref, getDownloadURL } from "firebase/storage";
// Create a reference to the file we want to download
const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');
// Get the download URL
getDownloadURL(starsRef)
.then((url) => {
// Insert url into an <img> tag to "download"
})
.catch((error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
// File doesn't exist
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
// ...
case 'storage/unknown':
// Unknown error occurred, inspect the server response
break;
}
});
Download a file from its URL
import { getStorage, ref, getDownloadURL } from "firebase/storage";
const storage = getStorage();
getDownloadURL(ref(storage, 'images/stars.jpg'))
.then((url) => {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = (event) => {
const blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
// Or inserted into an <img> element
const img = document.getElementById('myimg');
img.setAttribute('src', url);
})
.catch((error) => {
// Handle any errors
});
File metadata
Update metadata
import { getStorage, ref, updateMetadata } from "firebase/storage";
// Create a reference to the file whose metadata we want to change
const storage = getStorage();
const forestRef = ref(storage, 'images/forest.jpg');
// Create file metadata to update
const newMetadata = {
cacheControl: 'public,max-age=300',
contentType: 'image/jpeg'
};
// Update metadata properties
updateMetadata(forestRef, newMetadata)
.then((metadata) => {
// Updated metadata for 'images/forest.jpg' is returned in the Promise
}).catch((error) => {
// Uh-oh, an error occurred!
});
Get metadata
import { getStorage, ref, getMetadata } from "firebase/storage";
// Create a reference to the file whose metadata we want to retrieve
const storage = getStorage();
const forestRef = ref(storage, 'images/forest.jpg');
// Get metadata properties
getMetadata(forestRef)
.then((metadata) => {
// Metadata now contains the metadata for 'images/forest.jpg'
})
.catch((error) => {
// Uh-oh, an error occurred!
});
Delete metadata
import { getStorage, ref, updateMetadata } from "firebase/storage";
const storage = getStorage();
const forestRef = ref(storage, 'images/forest.jpg');
// Create file metadata with property to delete
const deleteMetadata = {
contentType: null
};
// Delete the metadata property
updateMetadata(forestRef, deleteMetadata)
.then((metadata) => {
// metadata.contentType should be null
}).catch((error) => {
// Uh-oh, an error occurred!
});
Custom metadata
const metadata = {
customMetadata: {
'location': 'Yosemite, CA, USA',
'activity': 'Hiking'
}
};
List files
List all files
import { getStorage, ref, listAll } from "firebase/storage";
const storage = getStorage();
// Create a reference under which you want to list
const listRef = ref(storage, 'files/uid');
// Find all the prefixes and items.
listAll(listRef)
.then((res) => {
res.prefixes.forEach((folderRef) => {
// All the prefixes under listRef.
// You may call listAll() recursively on them.
});
res.items.forEach((itemRef) => {
// All the items under listRef.
});
}).catch((error) => {
// Uh-oh, an error occurred!
});
Paginate a list
import { getStorage, ref, list } from "firebase/storage";
async function pageTokenExample(){
// Create a reference under which you want to list
const storage = getStorage();
const listRef = ref(storage, 'files/uid');
// Fetch the first page of 100.
const firstPage = await list(listRef, { maxResults: 100 });
// Use the result.
// processItems(firstPage.items)
// processPrefixes(firstPage.prefixes)
// Fetch the second page if there are more elements.
if (firstPage.nextPageToken) {
const secondPage = await list(listRef, {
maxResults: 100,
pageToken: firstPage.nextPageToken,
});
// processItems(secondPage.items)
// processPrefixes(secondPage.prefixes)
}
}