删除带有下载网址的 Firebase 存储图像网址

Roh*_*hit 6 firebase firebase-realtime-database google-cloud-functions firebase-storage

我使用 Firebase 存储和实时数据库分别存储图像及其下载 url。文件名以随机方式生成,下载 url 生成并保存到实时数据库中。

场景:如果用户上传新图像(例如个人资料图像),我想借助 downloadImageurl 删除旧图像(下载图像 url 在最初上传图像时生成,并保存在实时数据库中)。旧图像如何可以删除吗?我已经尝试过下面的代码,但为了让它工作,我必须获取文件名。

gcs
            .bucket("e**********.appspot.com") // find it in Firebase>Storage>"gs://...." copy without gs 
             //or go to console.cloud.google.com/ buckets and copy name
            .file("images/" +event.params.uid+"/"+filename) //file location in my storage
            .delete()
            .then(() => {
                console.log(`gs://${bucketName}/${filename} deleted.`);
            })
            .catch(err => {
                console.error('ERROR-DELETE:', err+ " filename: "+filename);
            });
Run Code Online (Sandbox Code Playgroud)

Die*_*ego 0

取决于你想要什么:

  1. 保留原始图像并可以在将来手动删除它。
  2. 生成缩略图后立即将其删除。

我想你正在使用这个例子

1-您必须将文件路径存储在数据库中。然后每当你想从前面删除它时:

import * as firebase from 'firebase';
...
const store = firebase.storage().ref();
// Depending on which db you use and how you store, you get the filePath and delete it:
store.child(image.filePath).delete();
Run Code Online (Sandbox Code Playgroud)

2-继续 firebase 函数的承诺,如下所示:

// ...LAST PART OF THE EXAMPLE...
.then(() => {    
// Add the URLs to the Database
return admin.database().ref('images').push({path: fileUrl, thumbnail: thumbFileUrl});
}).then(() => {
// ...PART YOU CAN ADD TO DELETE THE IMAGE UPLOADED
const bucket = gcs.bucket(bucket);
bucket.file(filePath).delete();
})
Run Code Online (Sandbox Code Playgroud)

“bucket”是之前创建的 const:

const bucket = gcs.bucket(event.data.bucket);
Run Code Online (Sandbox Code Playgroud)

以及“文件路径”:

const filePath = event.data.name;
Run Code Online (Sandbox Code Playgroud)