Reputation:
I am a beginner in Javascript.
All I want to do is to store a file in Firestorage, and then keep the URL link in a variable. However, right now, the URL is not kept, and my variable is empty.
const pictureUrl = ''
// Upload picture part
var refname = 'profile_pictures/' + "Picture" + "_" + "Name";
let storageRef = firebase.storage().ref(refname);
let firstFile = document.getElementById("pictureImported").files[0]
let uploadTask = storageRef.put(firstFile).then(function(fileSnapshot) {
fileSnapshot.ref.getDownloadURL().then(url => pictureUrl = url)
})
console.log(pictureUrl);
The console.log gives a blank line. What should I do to really save the url?
Upvotes: 0
Views: 63
Reputation: 80934
pictureUrl
will only have a value inside the then()
since getDownloadUrl()
is asynchronous. If you want to the pictureUrl
outside the then()
method then do the following:
function storeImage(firstFile){
return new Promise((resolve, reject) => {
let uploadTask = storageRef.put(firstFile).then((fileSnapshot)=> {
fileSnapshot.ref.getDownloadURL().then(url => {
pictureUrl = url;
resolve(pictureUrl);
});
});
}
Then to access the url
you can do:
storageImage(file).then((value) => {
console.log(value);
});
Check here for more info:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
Upvotes: 1