这是使用 Firebase 函数删除 Firebase 存储文件夹中文件的一种解决方案。
它假定您在 Firebase 数据库中的 /MyStorageFilesInDatabaseTrackedHere/path1/path2 下存储了模型。
这些模型将有一个名为“文件名”的字段,该字段将具有 Firebase 存储中文件的名称。
工作流程是:
- 删除 Firebase 数据库中包含模型列表的文件夹
- 通过 Firebase 函数监听该文件夹的删除
- 此函数将遍历文件夹的子文件夹,获取文件名并在 Storage 中将其删除。
(免责声明:Storage 中的文件夹在此函数结束时仍然存在,因此需要再次调用才能将其删除。)
// 1. Define your Firebase Function to listen for deletions on your path
exports.myFilesDeleted = functions.database
.ref('/MyStorageFilesInDatabaseTrackedHere/{dbpath1}/{dbpath2}')
.onDelete((change, context) => {
// 2. Create an empty array that you will populate with promises later
var allPromises = [];
// 3. Define the root path to the folder containing files
// You will append the file name later
var photoPathInStorageRoot = '/MyStorageTopLevelFolder/' + context.params.dbpath1 + "/" + context.params.dbpath2;
// 4. Get a reference to your Firebase Storage bucket
var fbBucket = admin.storage().bucket();
// 5. "change" is the snapshot containing all the changed data from your
// Firebase Database folder containing your models. Each child has a model
// containing your file filename
if (change.hasChildren()) {
change.forEach(snapshot => {
// 6. Get the filename from the model and
// form the fully qualified path to your file in Storage
var filenameInStorage = photoPathInStorageRoot + "/" + snapshot.val().filename;
// 7. Create reference to that file in the bucket
var fbBucketPath = fbBucket.file(filenameInStorage);
// 8. Create a promise to delete the file and add it to the array
allPromises.push(fbBucketPath.delete());
});
}
// 9. Resolve all the promises (i.e. delete all the files in Storage)
return Promise.all(allPromises);
});