5

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) {

    });
});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
mik
  • 799
  • 9
  • 31
  • 1
    Possible duplicate of [Get Download URL from file uploaded with Cloud Functions for Firebase](https://stackoverflow.com/questions/42956250/get-download-url-from-file-uploaded-with-cloud-functions-for-firebase) – Doug Stevenson Oct 17 '17 at 19:07

1 Answers1

5

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.

mik
  • 799
  • 9
  • 31