首页 文章

使用下载网址删除Firebase存储图片网址

提问于
浏览
1

我使用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);
            });

2 回答

  • 1

    根据您的需要:

    • 保留原始图像,以后可以手动删除它 .

    • 生成缩略图后立即删除它 .

    我想你正在使用this example

    1-您必须将filePath存储在数据库中 . 然后,只要您想从前面删除它:

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

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

    “bucket”是先前创建的const:

    const bucket = gcs.bucket(event.data.bucket);
    

    以及“filePath”:

    const filePath = event.data.name;
    
  • 0

    这可能会帮到你 .

    此代码将从URL获取文件名,并将删除该文件 . 目前这个解决方案适合我!

    Code

    import * as firebase from 'firebase';
    ...
    let name = imagePath.substr(imagePath.indexOf('%2F') + 3, (imagePath.indexOf('?')) - (imagePath.indexOf('%2F') + 3));
    name = name.replace('%20',' '); 
    let storagePath = firebase.storage().ref();
    storagePath.child(`images/${name}`).delete();
    

相关问题