Get Download URL from file uploaded with Cloud Functions for Firebase

后端 未结 23 1813
春和景丽
春和景丽 2020-11-22 01:19

After uploading a file in Firebase Storage with Functions for Firebase, I\'d like to get the download url of the file.

I have this :

...

return buck         


        
23条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 01:51

    If you're working on a Firebase project, you can create signed URLs in a Cloud Function without including other libraries or downloading a credentials file. You just need to enable the IAM API and add a role to your existing service account (see below).

    Initialize the admin library and get a file reference as your normally would:

    import * as functions from 'firebase-functions'
    import * as admin from 'firebase-admin'
    
    admin.initializeApp(functions.config().firebase)
    
    const myFile = admin.storage().bucket().file('path/to/my/file')
    

    You then generate a signed URL with

    myFile.getSignedUrl({action: 'read', expires: someDateObj}).then(urls => {
        const signedUrl = urls[0]
    })
    

    Make sure your Firebase service account has sufficient permissions to run this

    1. Go to the Google API console and enable the IAM API (https://console.developers.google.com/apis/api/iam.googleapis.com/overview)
    2. Still in the API console, go to the main menu, "IAM & admin" -> "IAM"
    3. Click edit for the "App Engine default service account" role
    4. Click "Add another role", and add the one called "Service Account Token Creator"
    5. Save and wait a minute for the changes to propagate

    With a vanilla Firebase config, the first time you run the above code you'll get an error Identity and Access Management (IAM) API has not been used in project XXXXXX before or it is disabled.. If you follow the link in the error message and enable the IAM API, you'll get another error: Permission iam.serviceAccounts.signBlob is required to perform this operation on service account my-service-account. Adding the Token Creator role fixes this second permission issue.

提交回复
热议问题