Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to getDownloadURL in a Firebase Function

When using Firebase Storage to store images, there is a URL to the image that looks like this : https://firebasestorage.googleapis.com/v0/b/[MY-APP].appspot.com/o/[FILE-NAME]?alt=media&token=[TOKEN]

I want to get this URL.

According to this, this, and this and this, I need to use the .getDownloadURL() method, which is on the "storage ref" .. but the documentation of the available objects does not fit with the actual object.

And when I attempt to access the .getDownloadURL() method on the objects suggested by the documentation in the code below I get various property not found errors.

        const admin = require('firebase-admin');
        admin.initializeApp();

        admin
        .storage()
        .bucket()
        .upload(imageToBeUploaded.filepath, {
            destination: storageFolder,
            resumable: false,
            metadata: {
                metadata: {
                contentType: imageToBeUploaded.mimetype
                }
        }
        })
        .then((taskSnapshot) => {
            // HOW DO I GET THE DOWNLOADABLE URL 
        })

I've tried the following :

taskSnapshot[1].getDownloadURL(),

admin.storage().ref(storageFolder+'/'+imageFileName).getDownloadURL(),

admin.storageRef(storageFolder+'/'+imageFileName).getDownloadURL(),

admin.storage().ref().child(storageFolder+'/'+imageFileName).getDownloadURL(),

.. and a bunch of others.

Trial and error is not finding the "storageRef" that has that method,

How can I get the downloadable url for my image ?

like image 242
kris Avatar asked Dec 13 '22 10:12

kris


1 Answers

The solution I've used is to first change the access rules for my storage bucket, like so :

https://console.firebase.google.com/u/0/project/[MY_APP]/storage[MY_APP].appspot.com/rules

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read;
      allow write: if request.auth != null;
    }
  }
}

which means the token is not required on the URL in order to be able to view the image.

And then I have just hardcoded the URL :

            .then((taskSnapshot) => {
                const imageUrl = `https://firebasestorage.googleapis.com/v0/b/` +
                                 `${MY_APP_ID}.appspot.com/o/${imageFileName}?alt=media`;
                return imageUrl;
            })
like image 160
kris Avatar answered Jan 10 '23 22:01

kris