Get Started With Firebase Storage
Published: 2021-05-10 00:29:45

# Get Started With Firebase Storage (Web)

Firebase is a developing platform provided by Google to the developers to build dynamic web apps or any mobile apps. Moreover, firebase is providing a lot of features such as Firebase authentication to quickly authenticate the user with the auth state change listener, Real-time database to store the relevant data in JSON like format, Cloud Firestore scalable database keeps your data in-sync across client apps through realtime listeners, and lot more features.
Today, I will be going to talk about a feature that is Firebase Storage and how we can implement it in our web apps. I will specifically discuss the core feature of Firebase Storage. So let's get started.

# What does Firebase Storage provide to the developers?

Certainly, Firebase Storage is one of the core features to Firebase development platform that lets you upload and share rich content such as images, files, videos into your apps. Cloud Storage lets you securely upload these files directly from mobile devices and web browsers, handling spotty networks with ease. Moreover, the following data is stored in a Google Cloud Storage bucket with a large scale storage solution and high availability.

# How to implement Firebase Storage in our project?

First, we need to create a firebase project. Follow the steps to create a firebase project so that we could use Firebase Storage functionality to store the image:

1. Go to firebase.google.com and sign in
2. After sign in, click the 'go-to console' tab.
3. Click 'Add project'; then enter your project name, and click continue.
4. Disable Google Analytics for this project as of now. However, if you have a google analytics account, then you can enable it for your requirements.
5. Finally, click create a project button. Wait for creating the project and click continue.

![firebase storage 1](/blog-images/firebaseStorage1.png)

For this tutorial project, I am going to create a directory named 'image-uploader' (you can choose any name). And inside the directory, I will create two files - **index.html and app.js**. I will be using the **Bootstrap 4 framework** to build awesome CSS design.

**_NOTE - For this tutorial, I am using the VSCode editor to implement the code. You can choose any code editor comfortable with it._**

We have to create a connection with the firebase project so that we could upload the images to the Firebase Storage. For that, follow the steps:

![firebase storage 2](/blog-images/firebaseStorage2.png)

1. Click the web icon, enter the app name like image-uploader, and click register app.
2. Now, you would see the firebase SDK codes. Copy the starting script link and paste it inside the index.html between the head tag.
3. And lastly, copy the last script code and paste it inside the app.js file.
4. You need to add Bootstrap 4 CSS CDN link, Firebase Storage CDN link, and connect app.js to index.html file.

**Bootstrap 4.1.3 CSS CDN link -** `<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">`
**Firebase Storage CDN link -** `<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-storage.js"></script>`

We need to set up the storage so that anybody can upload the image without authentication. For this follow the steps:

![firebase storage 7](/blog-images/firebaseStorage7.png)

1. Go the project main screen, click the storage option(left panel).
2. Click get started, click next, and choose the Cloud Storage location and click done.
3. Go to the Rules tab, replace 'if request.auth != null' with 'if true', and click publish.

![firebase storage 9](/blog-images/firebaseStorage9.png)

# Index.html

We are going to create a button to select the image from our local machine. And the image directly uploads to the firebase storage.

```html
<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-storage.js"></script>
        <title>Image-uploader</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    </head>
    <body>
        <div class="container mt-5">
            <h3 class="mb-4" >Image Upload</h3>
            <div class="jumbotron" >
                <input class="btn btn-primary" type="file" id="imageUpload">
            </div>
            <h5 id="progessIndicator">upload progress: 0%</h5>
        </div>
        <script src="app.js" ></script>
    </body>
</html>
```

# script.js

First, we need to create a storage reference to refer to the storage location. In the code, we can provide content type to upload the exact content to the storage. I have to implement addEventListener to listen to the image changes by the user. Inside the listener function, I used a file variable to get the file i.e image file. With the help of storageRef variable, I am uploading the image to the firebase storage. All the images reside in the child directory named 'images'. And, also progress indicator indicates the current uploading progress in percentage that reflects on the screen.

```javascript
var firebaseConfig = {
  apiKey: "Your API KEY", //replace with your key
  authDomain: "image-uploader-a5a2c.firebaseapp.com",
  databaseURL: "https://image-uploader-a5a2c.firebaseio.com",
  projectId: "image-uploader-a5a2c",
  storageBucket: "image-uploader-a5a2c.appspot.com",
  messagingSenderId: "1016001991019",
  appId: "1:1016001991019:web:9cd7eb0ebfdbea5e45fc2e",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

//storage reference
const storageRef = firebase.storage().ref();

var imageUploader = document.getElementById("imageUpload");
var progessIndicator = document.getElementById("progessIndicator");

//metadata to store specific file type
const metadata = {
  contentType: "image/jpeg",
};

//listening the on change image file
imageUploader.addEventListener("change", (e) => {
  //holding the img
  var file = e.target.files[0];

  //uploading the img on firebase storage
  var uploadImage = storageRef.child("images/" + file.name).put(file, metadata);

  uploadImage.on("state_changed", function (snapshot) {
    var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    progessIndicator.textContent = `upload progress: ${progress}%`;
  });
});
```

![firebase storage 10](/blog-images/firebaseStorage10.png)

![firebase storage 3](/blog-images/firebaseStorage3.png)

## How to know whether the image is uploaded or not?

Go the project main screen, click the storage option(left panel). Now you can see a folder named image and inside the folder, all the images are stored.
**For More Information -** Click Here [Firebase Storage](https://firebase.google.com/docs/storage)