0

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

}
1
  • The error is telling you that uploaded_image doesn't have a method called ref(). What are you expecting that's different? Have you gone through the documentation for getting download URLs? firebase.google.com/docs/storage/web/download-files Commented Feb 22, 2020 at 19:03

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.