What is Firebase Cloud Storage? How to use it in your web project?

What is Firebase Cloud Storage? How to use it in your web project?

This is part two of a three blog series on Firebase basics. In this one, we will read about Cloud Storage.

Firebase Cloud Storage allows you to upload and distribute user-generated information like photographs and videos, allowing you to incorporate rich media into your apps.

It allows you to safely upload these files from mobile devices and web browsers, even over unstable networks. App developers that need to store and serve user-generated material, like images or videos, can utilize Cloud Storage for Firebase.


Create a default Cloud Storage bucket

  • Select Storage from the Firebase console's navigation bar, then click Get started.
  • Review the information on applying security rules to secure your Cloud Storage data. Consider establishing public access rules during development. You can read about security rules here
  • Choose a location for your Cloud Storage bucket's default location.

Note: You can't modify your project's default GCP resource location after it's been configured.

Creating a Reference

To upload, download, or delete files, you must first make a reference to the file you wish to work with. A reference can be compared to a pointer to a cloud file. References are small and lightweight, allowing you to build as many as you need while still being reusable for numerous operations.

To make a reference, first use getStorage() to get an instance of the Storage service, then use ref() with the service as a parameter. Now, this reference represents the Cloud Storage bucket's root.

import { getStorage, ref } from "firebase/storage";

const storage = getStorage();

// Create a child reference
const fruitImagesRef = ref(storage, 'fruitImages');
// fruitImagesRef now points to 'fruitImages'

// Child references can also take paths delimited by '/'
const appleRef = ref(storage, 'fruitImages/apple.jpg');
// appleRef now points to "fruitImages/apple.jpg"
// fruitImagesRef still points to "fruitImages"

Navigating using References

  • To navigate up the file hierarchy, you may also utilize the parent and root properties. root goes all the way to the top, while parent goes up one level.
import { getStorage, ref } from "firebase/storage";

const storage = getStorage();
const appleRef = ref(storage, 'fruitImages/apple.jpg');

// Parent allows us to move to the parent of a reference
const fruitImagesRef = appleRef.parent;
// fruitImagesRef now points to 'fruitImages'

// Root allows us to move all the way back to the top of our bucket
const rootRef = appleRef.root;
// rootRef now points to the root
  • Because child(), parent, and root each return a reference, they can be chained together several times. The only exception is that parent of root is null.
import { getStorage, ref } from "firebase/storage";

const storage = getStorage();
const appleRef = ref(storage, 'fruitImages/apple.jpg');

// References can be chained together multiple times
const mangoRef = ref(appleRef.parent, 'mango.jpg');
// mangoRef points to 'fruitImages/mango.jpg'

// nullRef is null, since the parent of root is null
const nullRef = appleRef.root.parent;

Properties of Reference

import { getStorage, ref } from "firebase/storage";

const storage = getStorage();
const mangoRef = ref(storage, 'fruitImages/mango.jpg');

// Reference's path is: 'fruitImages/mango.jpg'
// This is analogous to a file path on disk
mangoRef.fullPath;

// Reference's name is the last segment of the full path: 'mango.jpg'
// This is analogous to the file name
mangoRef.name;

// Reference's bucket is the name of the storage bucket where files are stored
mangoRef.bucket;

Uploading Files into storage

Cloud Storage for Firebase enables you to rapidly and simply upload files to a Firebase-provided and managed Cloud Storage bucket.

Upload from a Blob or File

After creating an appropriate reference, you call the uploadBytes() function. uploadBytes() transfers files to Cloud Storage using the JavaScript File and Blob APIs.

import { getStorage, ref, uploadBytes } from "firebase/storage";

const storage = getStorage();
const fruitImagesRef = ref(storage, 'fruitImages');

// 'file' comes from the Blob or File API
uploadBytes(storageRef, file).then((snapshot) => {
  console.log('Uploaded a blob or file!');
});

Managing Uploads

You may use the pause(), resume(), and cancel() methods to pause, resume, and cancel uploads in addition to starting them. Calling pause() or resume() will cause the pause or running status to change. When you call the cancel() function, the upload fails and returns an error stating that it was canceled.

import { getStorage, ref, uploadBytesResumable } from "firebase/storage";

const storage = getStorage();
const mongoRef = ref(storage, 'fruitImages/mongo.jpg');

// Upload the file and metadata
const uploadTask = uploadBytesResumable(mongoRef, file);

// Pause the upload
uploadTask.pause();

// Resume the upload
uploadTask.resume();

// Cancel the upload
uploadTask.cancel();

Downloading Files from storage

The getDownloadURL() function on a Cloud Storage reference may be used to obtain the download URL for a file.

import { getStorage ,ref , getDownloadURL } from "firebase/storage";

const storage = getStorage();
getDownloadURL(ref(storage, 'fruitImages/apple.jpg'))
  .then((url) => {
    // url is the download URL for 'fruitImages/apple.jpg'

    // This can be inserted into an <img> element
    const img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

Deleting files from storage

To remove a file, you must first make a reference to it. Then, on that reference, use the deleteObject() function, which returns a Promise that resolves or an error if the Promise rejects.

import { getStorage, ref, deleteObject } from "firebase/storage";

const storage = getStorage();

// Create a reference to the file to delete
const mongoRef = ref(storage, 'fruitImages/mongo.jpg');

// Delete the file
deleteObject(mongoRef).then(() => {
  // File deleted successfully
}).catch((error) => {
  // Uh-oh, an error occurred!
});

That was all for Firebase cloud storage, I have tried to explain all the basic concepts required for you to get started with uploading and downloading files from your web app.

In the forthcoming blog which is also the last blog in this series, we will learn about the Firebase authentication section and will also look into the security rules for the firestore and cloud storage.