Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a Firebase storage image link via Cloud Function

Tags:

How do I retrieve the download links to stored images in Firebase via a cloud function?

I've tried all kinds of variations including the next one:

exports.getImgs = functions.https.onRequest((req, res) => {
    var storage = require('@google-cloud/storage')();

var storageRef = storage.ref;

console.log(storageRef);

storageRef.child('users/user1/avatar.jpg').getDownloadURL().then(function(url) {

    });
});
like image 445
mik Avatar asked Oct 17 '17 16:10

mik


1 Answers

It annoyed me, so I will put the solution with a straight forward explanation to those who are looking for it.

1st, install GCD Storage using the firebase command line:

npm install --save @google-cloud/storage

Cloud function code:

const gcs = require('@google-cloud/storage')({keyFilename: 'service-account.json'});
const bucket = gcs.bucket('name-of-bucket.appspot.com');

const file = bucket.file('users/user1/avatar.jpg');
        return file.getSignedUrl({
          action: 'read',
          expires: '03-09-2491'
        }).then(signedUrls => {
            console.log('signed URL', signedUrls[0]); // this will contain the picture's url
    });

The name of your bucket can be found in the Firebase console under the Storage section.

The 'service-account.json' file can be created and downloaded from here:

https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk

And should be stored locally in your Firebase folder under the functions folder. (or other as long as change the path in the code above)

That's it.

like image 151
mik Avatar answered Sep 22 '22 05:09

mik