Stay organized with collectionsSave and categorize content based on your preferences.
Cloud Storage for Firebaseallows you to quickly and easily upload files to aCloud Storagebucket provided
and managed by Firebase.
Upload Files
To upload a file toCloud Storage, you first create a reference to the
full path of the file, including the file name.
Web
import{getStorage,ref}from"firebase/storage";// Create a root referenceconststorage=getStorage();// Create a reference to 'mountains.jpg'constmountainsRef=ref(storage,'mountains.jpg');// Create a reference to 'images/mountains.jpg'constmountainImagesRef=ref(storage,'images/mountains.jpg');// While the file names are the same, the references point to different filesmountainsRef.name===mountainImagesRef.name;// truemountainsRef.fullPath===mountainImagesRef.fullPath;// false
// Create a root referencevarstorageRef=firebase.storage().ref();// Create a reference to 'mountains.jpg'varmountainsRef=storageRef.child('mountains.jpg');// Create a reference to 'images/mountains.jpg'varmountainImagesRef=storageRef.child('images/mountains.jpg');// While the file names are the same, the references point to different filesmountainsRef.name===mountainImagesRef.name;// truemountainsRef.fullPath===mountainImagesRef.fullPath;// false
Once you've created an appropriate reference, you then call theuploadBytes()method.uploadBytes()takes files via the JavaScriptFileandBlobAPIs and uploads
them toCloud Storage.
Web
import{getStorage,ref,uploadBytes}from"firebase/storage";conststorage=getStorage();conststorageRef=ref(storage,'some-child');// 'file' comes from the Blob or File APIuploadBytes(storageRef,file).then((snapshot)=>{console.log('Uploaded a blob or file!');});
In addition to theFileandBlobtypes,uploadBytes()can also upload aUint8ArraytoCloud Storage.
Web
import{getStorage,ref,uploadBytes}from"firebase/storage";conststorage=getStorage();conststorageRef=ref(storage,'some-child');constbytes=newUint8Array([0x48,0x65,0x6c,0x6c,0x6f,0x2c,0x20,0x77,0x6f,0x72,0x6c,0x64,0x21]);uploadBytes(storageRef,bytes).then((snapshot)=>{console.log('Uploaded an array!');});
varbytes=newUint8Array([0x48,0x65,0x6c,0x6c,0x6f,0x2c,0x20,0x77,0x6f,0x72,0x6c,0x64,0x21]);ref.put(bytes).then((snapshot)=>{console.log('Uploaded an array!');});
If aBlob,File, orUint8Arrayisn't available, you can use theuploadString()method to upload a raw,base64,base64url, ordata_urlencoded string toCloud Storage.
Web
import{getStorage,ref,uploadString}from"firebase/storage";conststorage=getStorage();conststorageRef=ref(storage,'some-child');// Raw string is the default if no format is providedconstmessage='This is my message.';uploadString(storageRef,message).then((snapshot)=>{console.log('Uploaded a raw string!');});// Base64 formatted stringconstmessage2='5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';uploadString(storageRef,message2,'base64').then((snapshot)=>{console.log('Uploaded a base64 string!');});// Base64url formatted stringconstmessage3='5b6p5Y-344GX44G-44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';uploadString(storageRef,message3,'base64url').then((snapshot)=>{console.log('Uploaded a base64url string!');});// Data URL stringconstmessage4='data:text/plain;base64,5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';uploadString(storageRef,message4,'data_url').then((snapshot)=>{console.log('Uploaded a data_url string!');});
// Raw string is the default if no format is providedvarmessage='This is my message.';ref.putString(message).then((snapshot)=>{console.log('Uploaded a raw string!');});// Base64 formatted stringvarmessage='5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';ref.putString(message,'base64').then((snapshot)=>{console.log('Uploaded a base64 string!');});// Base64url formatted stringvarmessage='5b6p5Y-344GX44G-44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';ref.putString(message,'base64url').then((snapshot)=>{console.log('Uploaded a base64url string!');});// Data URL stringvarmessage='data:text/plain;base64,5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';ref.putString(message,'data_url').then((snapshot)=>{console.log('Uploaded a data_url string!');});
Since the reference defines the full path to the file, make sure that you are
uploading to a non-empty path.
Add File Metadata
When uploading a file, you can also specify metadata for that file.
This metadata contains typical file metadata properties such asname,size,
andcontentType(commonly referred to as MIME type).Cloud Storageautomatically infers the content type from the file extension where the file is
stored on disk, but if you specify acontentTypein the metadata it will
override the auto-detected type. If nocontentTypemetadata is specified and
the file doesn't have a file extension,Cloud Storagedefaults to the
typeapplication/octet-stream. More information on file metadata can be found
in theUse File Metadatasection.
Web
import{getStorage,ref,uploadBytes}from"firebase/storage";conststorage=getStorage();conststorageRef=ref(storage,'images/mountains.jpg');// Create file metadata including the content type/** @type {any} */constmetadata={contentType:'image/jpeg',};// Upload the file and metadataconstuploadTask=uploadBytes(storageRef,file,metadata);
// Create file metadata including the content typevarmetadata={contentType:'image/jpeg',};// Upload the file and metadatavaruploadTask=storageRef.child('images/mountains.jpg').put(file,metadata);
In addition to starting uploads, you can pause, resume, and cancel uploads using
thepause(),resume(), andcancel()methods. Callingpause()orresume()will raisepauseorrunningstate changes. Calling thecancel()method results in the upload failing and returning an error
indicating that the upload was canceled.
Web
import{getStorage,ref,uploadBytesResumable}from"firebase/storage";conststorage=getStorage();conststorageRef=ref(storage,'images/mountains.jpg');// Upload the file and metadataconstuploadTask=uploadBytesResumable(storageRef,file);// Pause the uploaduploadTask.pause();// Resume the uploaduploadTask.resume();// Cancel the uploaduploadTask.cancel();
// Upload the file and metadatavaruploadTask=storageRef.child('images/mountains.jpg').put(file);// Pause the uploaduploadTask.pause();// Resume the uploaduploadTask.resume();// Cancel the uploaduploadTask.cancel();
While uploading, the upload task may raise progress events in
thestate_changedobserver, such as:
Event Type
Typical Usage
running
This event fires when the task starts or resumes uploading, and is often
used in conjunction with thepauseevent. For larger
uploads this event may fire multiple times as a progress update.
pause
This event fires any time the upload is paused, and is often used in
conjunction with therunningevent.
When an event occurs, aTaskSnapshotobject is passed back. This snapshot
is an immutable view of the task at the time the event occurred.
This object contains the following properties:
Property
Type
Description
bytesTransferred
Number
The total number of bytes that have been transferred when this
snapshot was taken.
totalBytes
Number
The total number of bytes expected to be uploaded.
state
firebase.storage.TaskState
Current state of the upload.
metadata
firebaseStorage.Metadata
Before upload completes, the metadata sent to the server. After upload
completes, the metadata the server sent back.
task
firebaseStorage.UploadTask
The task this is a snapshot of, which can be used to
`pause`, `resume`, or `cancel` the task.
ref
firebaseStorage.Reference
The reference this task came from.
These changes in state, combined with the properties of theTaskSnapshotprovide a simple yet powerful way to monitor upload events.
Web
import{getStorage,ref,uploadBytesResumable,getDownloadURL}from"firebase/storage";conststorage=getStorage();conststorageRef=ref(storage,'images/rivers.jpg');constuploadTask=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 completionuploadTask.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 uploadedconstprogress=(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);});});
varuploadTask=storageRef.child('images/rivers.jpg').put(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 completionuploadTask.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 uploadedvarprogress=(snapshot.bytesTransferred/snapshot.totalBytes)*100;console.log('Upload is '+progress+'% done');switch(snapshot.state){casefirebase.storage.TaskState.PAUSED:// or 'paused'console.log('Upload is paused');break;casefirebase.storage.TaskState.RUNNING:// or '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/...uploadTask.snapshot.ref.getDownloadURL().then((downloadURL)=>{console.log('File available at',downloadURL);});});
There are a number of reasons why errors may occur on upload, including
the local file not existing, or the user not having permission to upload
the desired file. More information on errors can be found in theHandle Errorssection of the docs.
Full Example
A full example of an upload with progress monitoring and error handling
is shown below:
Web
import{getStorage,ref,uploadBytesResumable,getDownloadURL}from"firebase/storage";conststorage=getStorage();// Create the file metadata/** @type {any} */constmetadata={contentType:'image/jpeg'};// Upload file and metadata to the object 'images/mountains.jpg'conststorageRef=ref(storage,'images/'+file.name);constuploadTask=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 uploadedconstprogress=(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-errorsswitch(error.code){case'storage/unauthorized':// User doesn't have permission to access the objectbreak;case'storage/canceled':// User canceled the uploadbreak;// ...case'storage/unknown':// Unknown error occurred, inspect error.serverResponsebreak;}},()=>{// Upload completed successfully, now we can get the download URLgetDownloadURL(uploadTask.snapshot.ref).then((downloadURL)=>{console.log('File available at',downloadURL);});});
// Create the file metadatavarmetadata={contentType:'image/jpeg'};// Upload file and metadata to the object 'images/mountains.jpg'varuploadTask=storageRef.child('images/'+file.name).put(file,metadata);// Listen for state changes, errors, and completion of the upload.uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,// or 'state_changed'(snapshot)=>{// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploadedvarprogress=(snapshot.bytesTransferred/snapshot.totalBytes)*100;console.log('Upload is '+progress+'% done');switch(snapshot.state){casefirebase.storage.TaskState.PAUSED:// or 'paused'console.log('Upload is paused');break;casefirebase.storage.TaskState.RUNNING:// or '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-errorsswitch(error.code){case'storage/unauthorized':// User doesn't have permission to access the objectbreak;case'storage/canceled':// User canceled the uploadbreak;// ...case'storage/unknown':// Unknown error occurred, inspect error.serverResponsebreak;}},()=>{// Upload completed successfully, now we can get the download URLuploadTask.snapshot.ref.getDownloadURL().then((downloadURL)=>{console.log('File available at',downloadURL);});});
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]