【问题标题】:Retrieve URL from uploaded image on Firebase从 Firebase 上上传的图片中检索 URL
【发布时间】:2020-02-23 06:48:53
【问题描述】:

我已将图像上传到 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);

}

【问题讨论】:

标签: javascript firebase firebase-storage


【解决方案1】:

put() 方法和getDownloadURL() 方法都需要调用服务器来完成它们的工作。出于这个原因,他们返回了一个承诺,而您必须等待该承诺完成才能获得他们的结果。

此外,您只能在上传图片后获取图片的下载网址。所以你应该只在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);
    }
  }
}

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

另见:

【讨论】:

    【解决方案2】:

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

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

    另外,根据the docs,您实际上并不需要服务器告诉您 URL,因为您应该自己构建它。

    【讨论】:

      猜你喜欢
      • 2017-05-09
      • 2016-03-10
      • 2021-07-26
      • 2021-06-23
      • 2021-07-13
      • 2020-04-01
      • 2023-02-08
      相关资源
      最近更新 更多