Hassaan Raza
Hassaan Raza

Reputation: 197

Unable to get Download Link from Firebase Storage (Javascript)

i have successfully wrote the code to upload images to firebase storage but getting errors when trying to get its download link,

my purpose of getting the download link is to save it to the database and later retrieve the link and use it as source of a image tag.

FULL CODE:

 var ImgUrl;
 var ImgName;
    
    function uploader(){
        ImgName =  document.getElementById("namet").value;
        var uploadTask =  firebase.storage().ref('images/'+ImgName+'.png').put(files[0]);
    }

    document.getElementById("ImgUp").onclick = function(){
         uploader();
        
        firebase.storage().ref('images/'+ImgName+'.png').getDownloadURL().then(function(downloadURL) {
        ImgUrl= downloadURL;

        firebase.database().ref("Information/"+ ImgName).set({
            ImageName : ImgName,
            Link : ImgUrl
        });
    });
}

the upload is successful i can see the image in storage with proper name, but cannot get pass this line and the database remains empty:

firebase.storage().ref('images/'+ImgName+'.png').getDownloadURL().then(function(downloadURL)

Error1: Failed to load resource: the server responded with a status of 404 ()

Error2: Firebase Storage: Object 'images/asd.png' does not exist.

Upvotes: 0

Views: 150

Answers (1)

Hassaan Raza
Hassaan Raza

Reputation: 197

Solved it by putting a delay timer in between, the upload (to storage) and saving the link (to database).

THE MAGIC LINES:

        const delay = ms => new Promise(res => setTimeout(res, ms)); // make delay

        await delay(10000);//excute delay 10 seconds

Full Code:

    var ImgUrl;
    var ImgName;
    //---------------------------------------------------------------------------//
    const delay = ms => new Promise(res => setTimeout(res, ms)); // make delay
    //---------------------------------------------------------------------------//
    
    function uploader(){
        ImgName =  document.getElementById("namet").value;
        var uploadTask =  firebase.storage().ref('images/'+ImgName+'.png').put(files[0]);
    }

    document.getElementById("ImgUp").onclick =async function(){
        uploader();
    //---------------------------------------------------------------------------//
        await delay(10000);//excute delay
    //---------------------------------------------------------------------------//

        firebase.storage().ref('images/'+ImgName+'.png').getDownloadURL().then(function(downloadURL) {
        ImgUrl= downloadURL;

        firebase.database().ref("Information/"+ ImgName).set({
            ImageName : ImgName,
            Link : ImgUrl
        });
    });
}

Upvotes: 0

Related Questions