要从 Cloud Function 中删除 Cloud Storage for Firebase 中存储的文件,您需要基于以下内容创建 File 对象:
此文件附加到的 Bucket 实例;
文件名,
然后调用delete()方法
详见 Node.js 库文档https://cloud.google.com/nodejs/docs/reference/storage/2.0.x/File。
这是文档中的代码示例:
const storage = new Storage();
const bucketName = 'Name of a bucket, e.g. my-bucket';
const filename = 'File to delete, e.g. file.txt';
// Deletes the file from the bucket
storage
.bucket(bucketName)
.file(filename)
.delete()
.then(() => {
console.log(`gs://${bucketName}/${filename} deleted.`);
})
.catch(err => {
console.error('ERROR:', err);
});
根据您的问题,我了解到您的应用程序客户端没有存储桶和文件名,只有一个下载 URL(如果它是一个网络应用程序,可能通过 getDownloadURL 生成,或者其他类似的方法SDK)。
因此,挑战是从下载 URL 派生存储桶和文件名。
如果你查看下载 URL 的格式,你会发现它的组成如下:
https://firebasestorage.googleapis.com/v0/b/<your-project-id>.appspot.com/o/<your-bucket-name>%2F<your-file-name>?alt=media&token=<a-token-string>
因此,您只需使用一组 Javascript 方法(如 indexOf()、substring() 和/或 slice())从下载 URL 中提取存储桶和文件名。
根据上述情况,您的 Cloud Function 代码可能如下所示:
const storage = new Storage();
.....
exports.deleteStorageFile = functions.firestore
.document('deletionRequests/{requestId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const downloadUrl = newValue.downloadUrl;
// extract the bucket and file names, for example through two dedicated Javascript functions
const fileBucket = getFileBucket(downloadUrl);
const fileName = getFileName(downloadUrl);
return storage
.bucket(fileBucket)
.file(fileName)
.delete()
});