Using Firebase Storage In Your web Application
SUB-TITLE: A BEGINNER’S GUIDE TO IMPLEMENTING FIREBASE CLOUD BUCKET IN A WEB APPLIATION
TABLE OF CONTENTS:
INTRODUCTION
FIREBASE SETUP
FIREBASE CLOUD STORAGE SETUP
FIREBASE CLOUD STORAGE CONFIGURATION
SETTING UP YOUR WEB APPLICATION
INTEGRATING FIREBASE STORAGE TO YOUR WEB APPLICATION
IMPLEMENTING FILE UPLOAD AND DOWNLOADS
IMPLEMENTING OTHER ADDITIONAL FEATURES
CONCLUSION
INTRODUCTION
Hello User, In this tutorial, we would be walking down the path of setting up a notable Firebase feature which is popularly termed Cloud bucket in our web application. But first of all, what is Firebase all about?
Firebase is a cloud computing platform owned and maintained by Google which provides a wide range of software solutions and services for web users. Some of its features include Authentication, Database storage, Cloud Messaging, Web hosting, Data Analytics and many more. Of key importance is its cloud storage functionality which is used in storing user information not excluding texts, images, videos and other resources. This tutorial is structured in order to guide you on how to integrate Firebase cloud storage feature in your Web application which you can use to store and retrieve your application information.
The basic requirement needed to understand this tutorial include;
Basic knowledge of React JS (The web application we intend to create is based on this library)
Knowledge of NPM installation
A Google account in order to set up Firebase
Now let's begin.
FIREBASE SETUP:
Let’s head over to https://console.firebase.google.com.
Then click on Add Project. Our project name for this tutorial will be My-React-Database.
Since it’s a demo project, you might not need to enable Google analytics.
On your project home-page, kindly select Cloud Storage
Thereafter, click on Get Started
On the popup menu, select Start in Production mode. And click Next.
On the cloud storage location box, select the region closest to you, Mine is US-central. Thereafter, select Next.
FIREBASE CLOUD STORAGE CONFIGURATION
Having completed the steps above, let's now return to our project home page.
On the project home page screen, there are some SDKs (Software Development Toolkit) for web, android and ios devices. We would be using the Project’s web SDK. Click on the web SDK link. Upon successful completion of the above steps, you would be given a configuration code containing your storage API keys and other important credentials as seen in the image below. Ensure to copy it and store it as we would be making use of it in our tutorial.
SETTING UP YOUR WEB APPLICATION
Right now, we would be creating our React application using Create-React-App. To create a React web application, enter npm create-react-app React-database-app
into your command prompt.
Thereafter, wait for a few minutes and viola, we have our react app Working.
Then, navigate to the folder on command prompt and enter npm start
to run the application.
INTEGRATING FIREBASE STORAGE TO YOUR WEB APPLICATION
Now that we have our react app up and running, let’s go into the nitty-gritty of this project. We intend to create a web application where users can upload their files and get access to it and this we would learn using the firebase cloud bucket we just created.
We would begin by installing Firebase Npm package into our react project for easy integration of firebase cloud bucket into our react app.
Npm install firebase
We would then navigate to our src folder in the project and create a new file called firebase.js
in our code editor. This file will handle all the configurations we would work on in the next section.
Now that you have your file structure in place paste the firebase configuration code containing your app credentials in your firebase.js file.
Your firebase file should look like this.
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyA76iPn-bddcXGrDGknXGYBbMFphj2_Fqg",
authDomain: "react-database-4e2bc.firebaseapp.com",
projectId: "react-database-4e2bc",
storageBucket: "react-database-4e2bc.appspot.com",
messagingSenderId: "488000850843",
appId: "1:488000850843:web:8f84623fdd44be8b14af3e"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
Thereafter, we would then set up the storage functionality in the Firebase.js file. We would do this by importing the getStorage function into the Firebase application.
import {getStorage } from firebase/storage
getStorage is used to create an instance of Firebase Storage service in the web application. Your storage function is then initialized by integrating the app configuration into the getStorage function.
Export const storage = getStorage(app)
The final firebase js code is expected to look like this.
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
import {getStorage} from 'firebase/storage'
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyA76iPn-bddcXGrDGknXGYBbMFphj2_Fqg",
authDomain: "react-database-4e2bc.firebaseapp.com",
projectId: "react-database-4e2bc",
storageBucket: "react-database-4e2bc.appspot.com",
messagingSenderId: "488000850843",
appId: "1:488000850843:web:8f84623fdd44be8b14af3e"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const storage = getStorage(app);
Having completed this, let’s move on to designing our file upload page.
IMPLEMENTING FILE UPLOAD AND DOWNLOADS
We would then head over to our app.js page, delete the existing template and create our form for uploading our images.
import './App.css';
import React from 'react';
const App =() => {
return (
<div className="app">
<p> Hello, Welcome to ImgBackup. Kindly click on the button
below and send your images to the cloud!</p>
<form className="form">
<input type="image" />
<button type="submit" >Upload Me</button>
</form>
</div>
)
}
export default App;
This is the CSS code for styling
.app {
display: flex;
background-color: #1bb36c;
width: 100vw;
height: 100vh;
margin: 0 ;
flex-direction: column;
padding: 0;
justify-content: center;
}
.app-text {
display: flex;
font-size: 20px;
color: white;
font-weight: 600;
margin: 0 auto;
align-items: center;
vertical-align: middle;
text-align: center;
}
.form {
height: 100px;
display: flex;
flex-direction: column;
margin: 0 auto;
justify-content: center;
}
.form > button {
width: 100%;
height: 45px;
border-radius: 17px;
border-color: transparent;
background-color: white;
color: #1bb36c;
font-size: 20px;
text-align: center;
vertical-align: middle;
align-items: center;
margin-top: 10px;
}
.progress-percent {
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto;
font-size: 50px;
color: white;
}
Thereafter, let’s now configure our app to upload the images.
Firstly we would import the storage functionality from our Firebase.js
file and then use our UseState
Hook as a state manager for our file links. We would also be importing the storage methods from Firebase node package.
import {ref, getDownloadUrl, uploadBytes} from "firebase/storage"
Const [myImgUrl, setMyImgUrl] = useState(null);
The code is then expected to look like this.
import './App.css';
import React, {useState} from 'react';
import {storage } from '../firebase'
import {ref, getDownloadUrl, uploadBytesResumable} from "firebase/storage"
const App =() => {
const [myImglink, setMyImglink] = useState(null);
return (
<div className="app">
<p> Hello, Welcome to ImgBackup. Kindly click on the button
below and send your images to the cloud!</p>
<form className="form" onSubmit={handleSubmit}>
<input type="image" />
<button type="submit" >Upload Me</button>
</form>
</div>
)
}
export default App;
Now, let's delve deeper into the firebase terms that just introduced.
Ref:
this represents the specific location in the cloud storage and it is call as a function to send data to that location.
uploadBytesResumable():
This function takes the reference earlier created and the file we intend to upload to the cloud storage. Alternatively, uploadBytes
function can also work perfectly to do the same function. However, the comparative advantage uploadByteResumable
has is that it allows to easy pausing of the upload and it shows the progress at which the upload occurs.
getDownloadUrl():
This function is used to get the download link to the file we would upload to the cloud storage which can be used to view the image anytime.
So right now, having learned a few basics on these terminologies, let’s discuss further on the handleSsubmit function.
e.preventDefault();
This code prevents the web page from automatically reloading whenever the submit button is pressed.
const file =
e.target
[0].files[0];
This code locates the file intended to be upladed.
if(!file) {
return null;
}
This code serves as a conditional to prevent sending empty files. The submit function would abort if no file was selected.
const pictureRef = ref(storage, ${
file.name
} );
This code brings in the Firebase storage method and then sets the name of the file you intend to upload
const monitorUpload = uploadBytesResumable(pictureRef, file)
monitorUpload.on("file uploading...",
(snapshot) => {
const fileUpload = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
This function serves to monitor the rate of upload of the file and then returns the current percentage of the total file uploaded.
setUploadProgression(fileUpload)
This useState function sets the percentage uploaded and regularly updates it as it changes.
}, (err) => { alert(err) },
This returns an error code if any erro occurs during the upload process.
() => {
getDownloadUrl(monitorUpload.snapshot.ref).then((downloadLink) => {
setMyImg(downloadLink)
});
This function generates the imahge storage link from Firebase and provides a link to easily acces the file when necessary.
The Final code.
import './App.css';
import React, {useState} from 'react';
import {storage } from '../firebase'
import {ref, getDownloadUrl, uploadBytesResumable} from "firebase/storage"
const App =() => {
const [myImg, setMyImg] = useState(null);
const [uploadProgression, setUploadProgression] = useState(null);
const handleSubmit =(e) => {
e.preventDefault();
const file = e.target[0].files[0];
if(!file) {
return null;
}
const pictureRef = ref(storage, ${file.name} );
const monitorUpload = uploadBytesResumable(pictureRef, file)
monitorUpload.on("file uploading...",
(snapshot) => {
const fileUpload = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
setUploadProgression(fileUpload)
}, (err) => {
alert(err)
},
() => {
getDownloadUrl(monitorUpload.snapshot.ref).then((downloadLink) => {
setMyImg(downloadLink)
});
}
);
}
return (
<div className="app">
<p> Hello, Welcome to ImgBackup. Kindly click on the button
below and send your images to the cloud!</p>
<form className="form" onSubmit={handleSubmit}>
<input type="image" />
<button type="submit" >Upload Me</button>
</form>
{!myImg && <div className="progress-bar">
<p> {uploadProgression} %</p>
</div> }
{
myImg && <p><a href={myImg} Here is the link to the image </a></p>
}
</div>
)
}
export default App;
This is what you are expected to see when you run the application.
IMPLEMENTING OTHER ADDITIONAL FEATURES
While working on the tutorial, you might come across some errors probably due to network connectivity or improper API configuration. You can indicate in the comment section if you encounter any new peculiar errors with your application. You can also explore the Firebase database feature (FireStore) which includes the storage functionality and other added database roles. It functions efficiently well as a No SQL database and you can try it out as a frontend developer venturing into backend development.
CONCLUSION
Firebase cloud bucket is well suited and efficient in storing user data in your web application. Also, it supports a long range of data formats as it has a great diversity of operations.
With that, we have come to the end of the tutorial. I earnestly hope it has impacted you and enlightened your use of Firebase features. Feel free to check out my other relevant web development articles here. I would also love to read your comments and answer your queries. Thanks and keep on coding.