繁体   English   中英

从 Firebase 上上传的图片中检索 URL

[英]Retrieve URL from uploaded image on Firebase

我已将图像上传到 Firebase 存储,但是当我尝试检索 URL 时,我得到“uploaded_image.ref 不是函数”......

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

}

put()方法和getDownloadURL()方法都需要调用服务器来完成它们的工作。 因此,他们返回 promise,您必须等待 promise 完成才能获得结果。

此外,您只能在上传图片后获得下载 URL。 因此,您应该只在put()完成后调用getDownloadURL()

在看起来像这样的代码中:

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

如评论中所述, downloadUrl仅在回调可用。 如果您在其他地方使用它,它可能没有您想要的价值。 所以任何需要下载 URL 的代码都应该在回调中,或者从那里调用。

另见:

据我所知, .put() function 是异步的,因此您需要处理回调并在 function 中完成您的工作。 您可以使用 async、await 或仅使用闭包来执行此操作:

const uploaded_image = path.put(image).then((snapshot) => {
     alert("Done!");
   }); 

此外,根据文档,您实际上不需要服务器告诉您 URL,因为您应该自己构建它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM