Firebase Admin SDK to download/retrieve files on Google Cloud Storage

穿精又带淫゛_ 提交于 2019-12-23 03:01:42

问题


I'm trying to download some images that I have uploaded to my Google Cloud Storage (aka into buckets). I'm unable to use the .ref() method on any of my const storage or const bucket because they are part of the admin SDK. The admin.storage has only the method .bucket() (https://firebase.google.com/docs/reference/admin/node/admin.storage.Storage).

I'm able to access the buckets. bucket.getFiles() works, and the result comes out to be an Array of Files objects with a ton of metadata (like file name, bucket owner, etc.). How can I get my images from the cloud storage and insert them into html objects?

var admin = require("firebase-admin");

var serviceAccount = require("./randomDB-f12d3-admin-correctly-working.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://randomDB-f12d3.firebaseio.com",
  storageBucket: "randomDB-f12d3.appspot.com"
});

const gcs  = require("@google-cloud/storage");
gcs.projectId = "randomDB-f12d3";
gcs.keyFilename = "randomDB-f12d3-firebase-admin-correctly-working.json";

exports.getFile = functions.https.onRequest((req, res) => {
  
  cors(req, res, () => {
    if (req.method !== "GET") {
      return res.status(500).json({
        message: "Not allowed"
      });
    }

    const storage = admin.storage();
    const bucket = admin.storage().bucket();

    bucket.getFiles().then((result)=>{
      
      console.log(result);
      res.send(result);
    });

  });

});

回答1:


The Admin SDK for Cloud Storage is just a wrapper around the @google-cloud/storage module. When you call admin.storage(), what you're getting back is a Storage object from that library. With admin.storage().bucket(), you're getting the default storage Bucket for your project. From there, you should use file() to create a reference to files in that bucket and download them as needed.



来源:https://stackoverflow.com/questions/53599481/firebase-admin-sdk-to-download-retrieve-files-on-google-cloud-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!