0

I am using firebase and as you can see in the code I am updating the user's image url that is stored on the user table. Is there a way to delete the old image file that's still being stored in my storage bucket once an image is updated?

exports.uploadImage = (req, res) => {
  const BusBoy = require("busboy")
  const path = require("path")
  const os = require("os")
  const fs = require("fs")

  const busboy = new BusBoy({ headers: req.headers })

  let imageToBeUploaded = {}
  let imageFileName

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    if (mimetype !== `image/jpeg` && mimetype !== `image/png`) {
      return res.status(400).json({ error: `Not an acceptable file type` })
    }

    // my.image.png => ['my', 'image', 'png']
    const imageExtension = filename.split(".")[filename.split(".").length - 1]
    // 32756238461724837.png
    imageFileName = `${Math.round(
      Math.random() * 1000000000000
    ).toString()}.${imageExtension}`
    const filepath = path.join(os.tmpdir(), imageFileName)
    imageToBeUploaded = { filepath, mimetype }
    file.pipe(fs.createWriteStream(filepath))
  })

  busboy.on("finish", () => {
    admin
      .storage()
      .bucket(config.storageBucket)
      .upload(imageToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imageToBeUploaded.mimetype
          }
        }
      })
      .then(() => {
        const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`
        return db.doc(`/users/${req.user.uid}`).update({ imageUrl })
      })
      .then(() => {
        return res.json({ message: "image uploaded successfully" })
      })
      .catch(err => {
        console.error(err)
        return res.status(500).json({ error: "something went wrong" })
      })
  })
  busboy.end(req.rawBody)
}

Any suggestions would be greatly appreciated

Rob Terrell
  • 2,398
  • 1
  • 14
  • 36

1 Answers1

0

The best way for you to achieve that is by using a Cloud Function to be run, once you have a new upload of photo done on your function.

I would recommend you to take a look at the article Automatically delete your Firebase Storage Files from Firestore with Cloud Functions for Firebase, to get more information, on how to perform these automatic deletions with Cloud Functions. Besides that, on this post from the Community here, you can check that with node.js language.

On these other two posts from the Community, you can get more ideas and insights to achieve this goal.

Let me know if the information helped you!

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22