Reputation: 169
I have uploaded an image to Firebase storage, but when I try to retrieve the URL, I get "uploaded_image.ref is not a function" .....
HTML
<form>
<input id="select_Image" type="file" required>
<button type="submit">Upload Image</button>
</form>
JS
let image_url = "";
function uploadImage {
const image = input_image.files[0];
const path = storage.ref("imagefolder/" + image.name);
const uploaded_image = path.put(image);
const the_url = uploaded_image.ref().getDownloadURL();
image_url = the_url;
alert(image_url);
}
Upvotes: 0
Views: 1233
Reputation: 598668
Both the put()
method and the getDownloadURL()
method need to call the server to do their work. For that reason they return a promise, and you have to wait for that promise to complete to get their results.
In addition, you can only get the download URL for an image, after it's been uploaded. So you should only call getDownloadURL()
once the put()
has completed.
In code that'd look something like this:
function uploadImage {
const image = input_image.files[0];
const path = storage.ref("imagefolder/" + image.name);
path.put(image).then(function() {
path.getDownloadURL().then(function(url) {
alert(url);
}
}
}
As said in the comments, the downloadUrl
is only usable inside the callback. If you use it elsewhere it may not have the value you want it to have. So any code that requires the download URL should be inside the callback, or be called from there.
Also see:
Upvotes: 2
Reputation: 36319
From what I can tell, the .put()
function is async, so you need to handle the callback and do your work inside that function instead. You could do this with async, await, or just use a closure:
const uploaded_image = path.put(image).then((snapshot) => {
alert("Done!");
});
Also, according to the docs, you don't actually need the server to tell you the URL because you're supposed to construct it yourself.
Upvotes: 0