9

I have small bug in my program.

I have firebase Storage in my app. I wanna let the user to upload image to the storage.

the thing is when the user uploads image and then tries to upload another image. what the program does it overwrites the image was uploaded before.

what I want is to avoid "overwrite" when the user wants to upload another image. and keep both images in different file

let currentUser = Auth.auth().currentUser
    let StorageRefrenece = Storage.storage().reference()
    let posterImageRef =
        StorageRefrenece.child("posters").child(currentUser!.uid).child("posterOne.jpg")

Thnx

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
Nawaf
  • 333
  • 4
  • 10
  • Hi Gustavo, you could also delete it before replacing the file if you know it is a new image: "await ...child("posterOne.jpg").delete(); ...child("posterOne.jpg").putData(replacementData); " – Brandon Pillay Sep 27 '21 at 12:51

2 Answers2

6

That is happening because you're storing them with the same name. In Firebase Storage you're the one in charge to decide the name of the files, there is no ".childByAutoId()".

If you want to have different files, you can create random values to name them, that is well explained here: How does one generate a random number in Apple's Swift language?

Your final code should look like this:

StorageRefrenece.child("posters").child(currentUser!.uid).child(<#Any Random Value#>)
Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
0
  import { v4 as uuid } from "uuid";

  const unId = uuid();

  const handleSubmit = async () => {



  const imageRef = ref(storage, unId);
    uploadBytes(imageRef, image)
      .then(() => {
        getDownloadURL(imageRef)
          .then((url) => {
            console.log("Url received from firebase: ",url)
            setUrl(url);
           })
        })
}
Iva
  • 2,447
  • 1
  • 18
  • 28