1
votes

I'm trying to make a chat app in Ionic 2. So when a user sends an image within a chat, I upload it to Firebase storage and it gives me a URL to that image. When a user sends the same image again, the image is uploaded on Firebase again and it overwrites the previous image and gives a new URL which causes problem in the old image sent.

I know the obvious solution is to upload image by renaming it but I don't want to upload same image multiple times. Is there a smarter solution to this? Please suggest.

1

1 Answers

1
votes

You can check if the file already exist in Firebase Storage by calling getDownloadUrl().

ref.child('example.png').getDownloadURL()
.then(url => {
    // File exist
})
.catch(err => {
    // File didnt exist or other error
});

EDIT: To prevent upload of two different images with same name i would suggest making use of the customMetadata, to mark each image with a base64-encoded MD5 hash of the image. And then use this hash for comparison at upload time when you encounter an image with the same name. If it is different images with same name then you would have to rename the image. Make sure to repeat this process in order to handle the case of 2+ images with the same name.

Some pseudo-code to illustrate what i mean:

uploadImg(img){
    hash = create base64 md5 hash of image
    do {
        if(filename exist in storage){
            get storage file metadata in order to get a hold of its hash
            if(hash is equal to hash from storage){
               use file in storage instead
            }
            else{
                alter the filename eg. using a counter and make the do-while-loop run again
        }
        else{
            uploadFile(img, metadata containing hash)
        }
    }while(other file with same name exist in storage)
}