DEV Community

Cover image for How to upload images to Firebase like a Pro?
BHARGAB KALITA
BHARGAB KALITA

Posted on

How to upload images to Firebase like a Pro?

So the first question in which database should you use to upload the images? πŸ€”, cause we have both Firestore and Realtime Database in the Firebase, but we are not going to upload the images directly to the Firestore or Realtime Database due to limited size for each "Document" which is "1MB" 😬 set by Firebase, hence we are going to upload the image files to the Firebase Storage and then will take the Download URL and add that URL to the Firestore (or Realtime DB) πŸ˜‹

TLDR;

import Firebase from 'Firebase'
import { v4 as uuid } from "uuid";


  export default function Somefunction(){

    const storage = firebase.storage()
    const db = firebase.firestore()

    const upload = () => {
      const storageRef = storage.ref();
      const Imageref = storageRef.child(
          `images/${uuid()}-${Image.name}` 
        );
      await Imageref.put(Image);
      const ImageFileUrl = await Imageref.getDownloadURL();

      await db.collection("ImageUrls").add({
        image : ImageFileUrl
      })
    }

  return()
  }  
Enter fullscreen mode Exit fullscreen mode

PS: we are going to use React for this example

First Step: Setting our main file
image

Second Step: Writing our upload function
image

Third Step: Now we have a problem of repetition of the Image References if we upload images of same names or uploading the same image multiple times while will lead to failure in fetching Images with same names, so to fix that we will be using uuid (NPM Package)
image

Fourth Step: Since all the things are done, now the only thing left is to add the ImageFileUrl to Firestore
image

Yayyyyy, you have successfully uploaded the image and added it to the Firestore πŸŽ‰


Thanks for reading this far, I hope y'all will love this 😊

Top comments (0)