0
votes

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.

1
could you share a screenshot of the error?obnoxiousnerd
are you directly using firebase or firebase.app ?? Try using firebase.app.storage()obnoxiousnerd
Since uploader method does an async operation. You should wait for it to complete then run following code.Eldar
Eldar bro that was it, i was to wait see my answer.Hassaan Raza

1 Answers

0
votes

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
        });
    });
}