firebase 从云功能删除云存储中的文件

xkrw2x1b  于 2023-08-07  发布在  其他
关注(0)|答案(2)|浏览(117)

我试图使一个谷歌云功能删除链接到Firebase实时数据库中的人对象的图像。但是每次我得到“请求期间出错”错误(没有任何具体的错误代码,它只是未定义)。下面是一个函数代码:

const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
const gcs = require('@google-cloud/storage')({ 
  projectId: "PROJ_ID",
  keyFilename: "SERV_ACC.json LOCATED IN FUNCTIONS FOLDER"});

admin.initializeApp(functions.config().firebase);

exports.removePersonImage = 
functions.database.ref("users/{userId}/persons/{personId}")
 .onDelete((snapshot, context) => {
   const person = snapshot.val();    

   if (!person.photo || !person.photo.key) {
    console.log("Person doesn't have photo");
    return true;
   }

   var path = "user/" + context.params.userId + "/" + person.photo.key + ".jpg";

   console.log("Bucket path: " + path);

   return gcs.bucket(path)
    .delete()
    .then(() => {
      console.log("Image " + person.photo.key + " successfully deleted");
      return true;
    })
    .catch(err => {
      console.error("Failed to remove image " + person.photo.key);
      console.error("Error: " + err.message);
      return false;
    });
});

字符串

9bfwbjaz

9bfwbjaz1#

我认为你得到的是一个引用到一个带有文件路径的Bucket。
你应该首先创建一个Bucket的引用,然后在Bucket上使用file()方法来创建File对象。
首先从存储控制台中看到的根存储桶名称声明存储桶,但不包含gs://,如下所示:

const bucket = gcs.bucket("***projectname***.appspot.com");

字符串
然后用“目录”声明你的文件。

const file = bucket.file("user/" + context.params.userId + "/" + person.photo.key + ".jpg");


然后调用delete:

return file.delete()
    .then(() => {
    ....


参见https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Bucket#file
和https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Storage#bucket

kmbjn2e3

kmbjn2e32#

const storage = new Storage({
      credentials: {
        client_email: process.env.STORAGE_BUCKET_CLIENT_EMAIL,
        private_key: process.env.STORAGE_BUCKET_PRIVATE_KEY,
      },
      projectId: process.env.STORAGE_BUCKET_PROJECT_ID,
    });

 bucket = storage.bucket(process.env.STROAGE_BUCKET_NAME);

 const imageParts = user.thumbnail.split('/');\

  bucket.file(`${imageParts[imageParts.length - 1]}`)
      .delete()
      .then((res) => {})
      .catch((error) => {});

字符串

相关问题