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

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

本文介绍了从云功能删除云存储中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Google Cloud Function,以删除链接到Firebase实时数据库中人对象的图像.但是,每次我遇到请求时出错"错误(没有任何特定的error.code时,它都是未定义的) )..这是一个功能代码:

I'm trying to make a Google Cloud Function which deletes images linked to person object in Firebase realtime database.. But every time I'm getting "Error during request" error (without any specific error.code, it's just undefined).. Here is a function code:

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;
    });
});

推荐答案

我认为您正在获取具有文件路径的存储桶引用.

I think you are getting the reference to a Bucket with the path of a File.

您应该首先创建对存储桶的引用,然后在存储桶上使用file()方法创建File对象.

You should first create a reference to your Bucket and then use the file() method on the Bucket to create the File object.

首先使用您在存储控制台中看到的根存储桶名称声明存储桶,但不带gs://,如下所示:

First declare the bucket from the root bucket name you see in the Storage console but without gs://, as follows:

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

然后使用子存储桶(即目录")声明文件

Then declare your file with the sub-buckets (i.e. the "directories")

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

然后删除通话:

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

这篇关于从云功能删除云存储中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 11:01