Firebase云存储访问错误“admin.store(...).ref不是函数”

xkftehaa  于 2022-09-21  发布在  Node.js
关注(0)|答案(2)|浏览(127)

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

根据https://firebase.google.com/docs/storage/web/start官方指南和https://firebase.google.com/docs/storage/web/create-reference,此代码应该返回根引用

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

但它抛出了一个错误,即

TypeError:admin.store(...).ref不是函数

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
}

Node-v=>v7.7.4

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

8ftvxx2r

8ftvxx2r1#

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

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

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

尝试直接使用Google Cloud API:

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

编辑:这次编辑只是为了停止用两年前的一篇帖子吓唬人。截至2020年5月,上述答案仍然适用。

von4xj4u

von4xj4u2#

在下面的示例中,我从名为“图像”的现有FiRestore集合中提取图像引用。我交叉引用了“图像”集合和“帖子”集合,以便我只获得与特定帖子相关的图像。这不是必需的。

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

相关问题