Cloud Storage for Firebase 访问错误 "admin.storage(...).ref is not a function"

Cloud Storage for Firebase access error "admin.storage(...).ref is not a function"

我正在使用 Cloud Storage for Firebase,但不知道如何访问存储文件

根据https://firebase.google.com/docs/storage/web/start official guide and https://firebase.google.com/docs/storage/web/create-reference,这段代码应该返回根引用

let admin = require('firebase-admin')
admin.initializeApp({...})
let storageRef = admin.storage().ref()

但是它抛出一个错误

TypeError: admin.storage(...).ref is not a function

package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {...},
  "dependencies": {
    "@google-cloud/storage": "^1.5.1",
    "firebase": "^4.8.0",
    "firebase-admin": "~5.4.2",
    "firebase-functions": "^0.7.1",
    "pdfkit": "^0.8.3",
    "uuid": "^3.1.0"
  },
  "private": true
}

节点-v => v7.7.4

我的最终目标是下载文件或将 pdf 文件上传到存储空间。

您正在使用 Cloud Functions 和 Firebase Admin SDK 尝试访问您的存储桶。您引用的入门指南是关于 Firebase 的 Web API 的客户端 Web 应用程序,而不是 Admin 的。那里的功能不同,因为它使用不同的 SDK(即使它们的名称相同)。

您尝试访问的 Storage 对象没有 ref() 函数,只有 appbucket().

https://firebase.google.com/docs/reference/admin/node/admin.storage

尝试直接使用 Google Cloud APIs:

https://cloud.google.com/storage/docs/creating-buckets#storage-create-bucket-nodejs

-

编辑: 此编辑只是为了停止使用两年前的 post 来吓唬人。截至 2020 年 5 月,上述答案仍然适用。

在下面的示例中,我从名为 "images" 的现有 Firestore 集合中提取图像引用。我将 "images" 集合与 "posts" 集合交叉引用,这样我只能得到与某个 post 相关的图像。这不是必需的。

Docs for getSignedUrl()

const storageBucket = admin.storage().bucket( 'gs://{YOUR_BUCKET_NAME_HERE}.appspot.com' )
const getRemoteImages = async() => {
    const imagePromises = posts.map( (item, index) => admin
        .firestore()
        .collection('images')
        .where('postId', '==', item.id)
        .get()
        .then(querySnapshot => {
            // querySnapshot is an array but I only want the first instance in this case
            const docRef = querySnapshot.docs[0] 
            // the property "url" was what I called the property that holds the name of the file in the "posts" database
            const fileName = docRef.data().url 
            return storageBucket.file( fileName ).getSignedUrl({
                action: "read",
                expires: '03-17-2025' // this is an arbitrary date
            })
        })
        // chained promise because "getSignedUrl()" returns a promise
        .then((data) => data[0]) 
        .catch(err => console.log('Error getting document', err))
    )
    // returns an array of remote image paths
    const imagePaths = await Promise.all(imagePromises)
    return imagePaths
}

这里是合并的重要部分:

const storageBucket = admin.storage().bucket( 'gs://{YOUR_BUCKET_NAME_HERE}.appspot.com' )
const fileName = "file-name-in-storage" // ie: "your-image.jpg" or "images/your-image.jpg" or "your-pdf.pdf" etc.
const remoteImagePath = storageBucket.file( fileName ).getSignedUrl({
    action: "read",
    expires: '03-17-2025' // this is an arbitrary date
})
.then( data => data[0] )

如果您只是想临时链接到云存储桶中文件夹中的所有图像,以下代码片段即可实现。在此示例中,我查询文件夹 images/userId.

下的所有图像
exports.getImagesInFolder = functions.https.onRequest(async (req, res) => {
    const storageRef = admin.storage().bucket('gs://{YOUR_BUCKET_NAME_HERE}');
    const query = {
        directory: `images/${req.body.userId}` // query for images under images/userId
    };
    
    const [files] = await storageRef.getFiles(query)
    const urls = await Promise.all(files.map(file => file.getSignedUrl({
        action: "read",
        expires: '04-05-2042' // this is an arbitrary date
    })))

    return res.send({ urls })
})

API 文档:

PS:请记住,这可能允许 任何人 传递 userId 和查询对于该特定用户的所有图像。