3
votes

I am using Firebase storage and Realtime Database for storing the image and its download url respectively.The filename is generated in a random manner with which download url is generated and saved to the realtime database.

Scenario: If user uploads new Image(For e.g Profile Image) I want to delete the old image with the help of downloadImageurl(Download image url is generated when image is uploaded initially and same is saved in the realtime database).How the old image can be deleted?I have tried below code but for it to work I must get filename.

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);
            });
4
Are you running this code in Cloud Functions? And you're using the Google Cloud Storage node API? It might be helpful if you provide more context about what's going on here.Doug Stevenson
@DougStevenson Yes I am using cloud function.Please find the updated questionRohit
I am using const gcs = require('@google-cloud/storage')(); and have followed the github tutorial to generate thumbnail image.Any help regarding this will be helpful to proceed furtherRohit
You could store both the path to the file in Storage as well as the download URL. When it comes time to delete the, you'll have its path available too.Doug Stevenson

4 Answers

3
votes

This may help you out.

This code will fetch the name of file from the URL and will delete that file. Currently this solution works for me!

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

Depending on what you want:

  1. Keep the original image and being able to delete it manually in the future.
  2. Delete it immediately after the thumbnail is generated.

I suppose you are using this example

1- You have to store the filePath in your db. Then whenever you want to delete it from your front:

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- Continue the promise from the firebase function like this:

// ...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" is the const previously created:

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

as well as "filePath":

const filePath = event.data.name;
0
votes

To delete an image with the url, you can use refFromUrl() function to get the ref then delete it easily

const storage = firebase.storage();
storage.refFromURL(imageUrl).delete()
0
votes
    const downloadUrl = "https://firebasestorage.googleapis.com/v0/b/***.appspot.com/o/***?alt=media&token=***";

The first *** represents FIREBASE_STORAGE_BUCKET
The second *** represents location of file in bucket
The third *** represents token for public access image/file

As a web developer, you're aware that URI are encoded such as "@" = "%40", "$" = "%24", " " = "%20", etc.

Since we are using JavaScript, what we can do is decode URI like so to get exact path

const path = decodeURIComponent(downloadUrl.split("o/")[1].split("?")[0]);

return await bucket
  .file(path)
  .delete()
  .then(() => true)
  .catch((error) => {
    throw new TypeError(`deleteImages ${error}`);
  });