Joshua Bitton
Joshua Bitton

Reputation: 403

deleting files from firebase storage

So I'm allowing user's upload certain images in the storage of firebase, and each file is named after their user id. So when a user uploads an image, I get a url that for that file

https://firebasestorage.googleapis.com/v0/b/jobify-a7a4a.appspot.com/o/CZx5biMydzQAOx4T8WXJU5jt2852%2Fimages%2Fdreamy-waterfall-4k-sc.jpg?alt=media&token=8e4d60ed-e956-4f71-80d1-58755fe94dbe

And so when a user changes the uploaded image, I'd like to delete the previously updated image from the storage. I've seen how they do it in the docs, but that requires the file name which I don't have access to.

This is the code when a user uploads an image

function uploadImg(e) {
const file = e.target.files[0];

if (file && file.size < 30000000) {
  var storageRef = firebase
    .storage()
    .ref(`${user.uid}/images`)
    .child(file.name);
  const task = storageRef.put(file);
  task.on(
    "state_changes",
    function progress(snap) {
      setLoading(true);
      const percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
      loadingref.current.style.height = percentage + "%";
    },
    function error() {
      setNotifibool(true);
      setNotifi({
        text: "Try Again!",
        icon: "fal fa-exclamation-circle"
      });
    },
    function complete() {
      setLoading(false);
      storageRef.getDownloadURL().then((url) => {
        setState(url);
      });
      setNotifi({
        text: "Image Uploaded!",
        icon: "fal fa-check-circle"
      });
    }
  );
} else {
  window.alert("too big");
}
}

Upvotes: 0

Views: 638

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598837

You can translate the download URL you have back to a reference by calling firebase.storage().refFromUrl(downloadUrl). Then your can delete the file by calling delete on that reference.

Upvotes: 2

Related Questions