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

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

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

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

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

但它抛出了一个错误,即

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

Package.json

  1. {
  2. "name": "functions",
  3. "description": "Cloud Functions for Firebase",
  4. "scripts": {...},
  5. "dependencies": {
  6. "@google-cloud/storage": "^1.5.1",
  7. "firebase": "^4.8.0",
  8. "firebase-admin": "~5.4.2",
  9. "firebase-functions": "^0.7.1",
  10. "pdfkit": "^0.8.3",
  11. "uuid": "^3.1.0"
  12. },
  13. "private": true
  14. }

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()的文档

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

以下是汇总的重要部分:

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

相关问题