如何在 Firebase 函数中获取下载 URL

kri*_*ris 3 firebase google-cloud-functions firebase-storage firebase-admin

使用 Firebase Storage 存储图像时,图像的 URL 如下所示: https ]?alt=media&token=[令牌]

我想得到这个网址。

根据thisthisthisthis,我需要使用该.getDownloadURL()方法,该方法位于“存储引用”..但可用对象的文档与实际对象不符。

当我尝试访问.getDownloadURL()下面代码中文档建议的对象上的方法时,我收到了各种未找到属性的错误。

        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 
        })
Run Code Online (Sandbox Code Playgroud)

我试过以下:

taskSnapshot[1].getDownloadURL(),

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

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

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

.. 和一堆其他人。

反复试验没有找到具有该方法的“storageRef”,

如何获取我的图片的可下载网址?

kri*_*ris 9

我使用的解决方案是首先更改我的存储桶的访问规则,如下所示:

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这意味着 URL 上不需要令牌才能查看图像。

然后我刚刚对 URL 进行了硬编码:

            .then((taskSnapshot) => {
                const imageUrl = `https://firebasestorage.googleapis.com/v0/b/` +
                                 `${MY_APP_ID}.appspot.com/o/${imageFileName}?alt=media`;
                return imageUrl;
            })
Run Code Online (Sandbox Code Playgroud)