[英]How to get DownloadURL from Firebase Storage
我正在存储Firebase上工作,我试图获取URL并将其设置为变量,但不幸的是我无法执行此操作,我的代码有问题。 有人可以帮我吗?
这是错误:
firebase.js:1未捕获(承诺)错误:Reference.push失败:第一个参数包含未定义的属性'PostUsers.ImageURL.i'
这是代码:
console.log('Nice, The file has been successfully uploaded to the Firebase storage!');
var DownloadURL = uploadTask.snapshot.downloadURL;
var Url_File = uploadTask.snapshot.ref.getDownloadURL().then(function (URL) {
return URL;
});
alert(Url_File);
uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
console.log('File available at', downloadURL);
//Url_File = downloadURL;
});
//getting the publication time
var dayObj = new Date();
var day = dayObj.getDate();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var month = monthNames[dayObj.getMonth()]
var year = dayObj.getFullYear();
var hour = dayObj.getHours();
var minutes = dayObj.getMinutes();
var seconds = dayObj.getSeconds();
var GlobalUserName = <%=Session["UserId"] %>;
firebase.database().ref('PostUsers/').push({
ImageURL: Url_File,
userAuthor: GlobalUserName,
day: day,
month: month,
year: year,
hour: hour,
minutes: minutes,
seconds: seconds
});
//console.log('the download Url of your file is: '+ downloadURL);
console.log('User post successfully added to realtime data bases');
});
我已经尝试了许多不同的方法,但是它们都无法正常工作。
提前致谢。
在这段代码中:
var Url_File = uploadTask.snapshot.ref.getDownloadURL().then(function (URL) {
return URL;
});
下载URL在名为URL
的变量的promise回调中。 它不在Url_File
。 Url_File
将包含then()
返回的promise。
您需要将使用下载URL的代码放在第一次可用的promise回调中。 您现在拥有的方式是,在URL可用之前,正在执行使用下载URL的代码。
下载URL仅在从getDownloadURL()
获得的then
回调中可用。 您不能在此之外访问它。
因此,解决办法是将需要下载的URL 步入回调的所有代码:
uploadTask.snapshot.ref.getDownloadURL().then(function (URL) {
//getting the publication time
var dayObj = new Date();
var day = dayObj.getDate();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var month = monthNames[dayObj.getMonth()]
var year = dayObj.getFullYear();
var hour = dayObj.getHours();
var minutes = dayObj.getMinutes();
var seconds = dayObj.getSeconds();
var GlobalUserName = <%=Session["UserId"] %>;
firebase.database().ref('PostUsers/').push({
ImageURL: URL,
userAuthor: GlobalUserName,
day: day,
month: month,
year: year,
hour: hour,
minutes: minutes,
seconds: seconds
});
console.log('User post successfully added to realtime database');
});
在处理现代Web API时,这是一种非常常见的模式:它们都是异步的,因此您的代码必须对此进行处理。
有关更多信息,请参见:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.