首页 > 解决方案 > Retrieve URL from uploaded image on Firebase

问题描述

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

}

标签: javascriptfirebasefirebase-storage

解决方案


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:


推荐阅读