javascript - 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);
}
解决方案
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:
推荐阅读
- java - Java Integer (java.lang.Integer) 数组除法等数学运算
- jmeter - JMeter - JSR223 采样器中的 groovy MultipleCompilationErrorsException
- javascript - 无法在 aws 中获取 javascript 文件
- vhdl - VHDL 状态机正在跳过状态
- c++ - QFile::size() 和读取文件后部署的缓冲区大小不一样
- python - 如何使用 Python 在命令行中创建交互式应用程序,而不仅仅是返回输出的脚本?
- if-statement - 在 If 语句中舍入乘积
- wordpress - Facebook 没有找到 og:image 属性,但我在我的代码中查找了它,实际上它是用图像 url 明确声明的
- javascript - Spotify Web api 上的错误 400。需要帮助请
- python - 从任何位置对包裹的最佳参考