Firebase to get url


Firebase is a backend-as-a-service (BAAS) that provides different services. It includes authentication, cloud storage, hoisting, etc., in the services. Basically, it makes it easy for developers to integrate the authentication, database, etc., in the mobile or web application.

In this tutorial, we will explore the cloud storage of Firebase. We will learn to upload images in the Firebase cloud storage and get the URL of the image, which we can use anywhere.

Users should follow the steps below to set up the Firebase account and integrate it with a single-page web application.

  • Step 1 − First, Go to the website of Firebase and create an account.

  • Step 2 − Now, go the https://console.firebase.google.com/u/0/ to open a Firebase console.

  • Step 3 − Now, click on the ‘Create project’ button to start creating a new project.

  • Step 4 − Here, add the project name, accept the terms & conditions and click the ‘continue’ button.

  • Step 5 − Select the preferred location, accept the terms and conditions and click on the ‘create project’ button.

  • Step 6 − It will redirect you to the below page. Here, click on the ‘storage’ card element. After that, click on the ‘get started’ button.

  • Step 7 − Here, choose to start either in ‘test’ or ‘production’ mode. Here, we will choose in ‘test’ mode for testing purposes and click on the ‘next’ button.

  • Step 8 − Now, choose the preferred location for the storage which is nearest to you and click on the ‘Done’ button. It will start creating the default bucket for storage.

  • Step 9 − Creating a storage bucket will redirect you to the page below. From here, copy the storage bucket id which we will use in the example.

  • Step 10 − Now, Go to the ‘Rules’ tab and edit the rules. After that, add the code below to allow all users to upload the image file without authenticating.

rules_version = '2';
service firebase.storage {
   match /b/{bucket}/o {
      match /{allPaths=**} {
         // Allow access by all users
         allow read, write;
      }
   }
}

We have now completed the Firebase project setup to upload the images in the storage bucket.

Example

The example below invokes the uploadFile() function when a user uploads any image file. In the uploadFile() function, we upload the image file to the Firebase storage, get the image URL, and change the value of the ‘src’ attribute of the image with the URL.

Users should follow the below steps for the given example.

  • Step 1 − Add the Firebase CDN in the <head> tag to use Firebase in the single-page website.

  • Step 2 − In HTML, add a progress bar whose progress we will update from JavaScript according to the image upload percentage. Also, add input to upload the file, which should invoke the uplaodFile() function as the user uploads the file. Furthermore, add the ‘img’ element with an empty ‘src’ value, and we will initialize the ‘src’ value after getting the download URL.

  • Step 3 − In JavaScript, As user uploads the file access it, and store the unique file name to the ‘fileName’ variable using the Date() object.

  • Step 4 − Now, initialize the Firebase storage.

  • Step 5 − Now start uploading the image file to the preferred location in the bucket, and upload the progress value according to the uploaded percentage.

  • Step 6 − Once the upload completes, use the getDownalodURL() method to get the image URL and set it as a value of the ‘src’ attribute of the image to show on the web page.

In the output, users can observe that it shows the uploaded image.

<html>
<head>
   <!-- Include Firebase SDK -->
   <script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js"></script>
   <script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-storage.js"></script>
   <style>
      img {
         width: 500px;
         height: auto;
      }
   </style>
</head>
<body>
   <h2>Uploading image to <i>Firebase and getting URL.</i></h2>
   <h3>Upload image file below.</h3>
   <form>
      <!-- Showing image uploading progress bar -->
      <progress value = "0" id = "progressBar" max = "100"> 0% </progress> <br> <br>
      <!-- file input -->
      <input id = "file" type = "file" onchange = "uploadFile()"> <br> <br>
      <!-- Showing uploaded image -->
      <img src = "" alt = "" id = "uploadedImage">
   </form>
   <script>
      // Firebase configurations
      var config = {
         apiKey: "AIzaSyBsYILuhF4wOGOe0rFhPudhVWO3cGh2z18",
         authDomain: "localhost",
         projectId: "test-application-45005",
         storageBucket: "gs://test-application-45005.appspot.com",
      };
      
      // Initialize the Firebase app
      firebase.initializeApp(config);
      var currentFile;
      function uploadFile() {
         var fileInput = document.getElementById("file");
         
         // select the uploaded file
         currentFile = fileInput.files[0];

         // give a unique name to the file
         var fileName = "image-" + Date.now();

         // Give reference to the bucket path where we require to store the uploaded image
         var storageRef = firebase.storage().ref('/images/' + fileName);

         // upload file to selected storage reference
         var uploadingElement = storageRef.put(currentFile);

         // When uploading of the image starts, change the value of the progress bar
         uploadingElement.on('state_changed', (uploadingImage) => {
            var progress =
            (uploadingImage.bytesTransferred / uploadingImage.totalBytes) * 100;
            var progressBar = document.getElementById('progressBar');
            progressBar.value = progress;
         }, function (error) {
            console.log(error);
         }, function () {

            // Get the image URL
            uploadingElement.snapshot.ref.getDownloadURL().then(
            function (imageURL) {
               // set image URL as a value of the 'src' attribute of the image element
               let img = document.getElementById('uploadedImage');
               img.src = imageURL;
            });
         });
      }
   </script>
</body>
</html>

Users learned to upload the image to the Firebase cloud storage using JavaScript and get the image URL. In real-time applications, while using Firebase, it is very useful to get the URL of the uploaded image for the profile photo of users and other images.

Also, Firebase allows developers to do a very quick set-up to upload images and get its URL.

Updated on: 24-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements