ASWATHY
ASWATHY

Reputation: 55

How to display image from firebase storage using javascript?

I tried to upload an image to firebase storage and retrieve the image from firebase storage. But, the "retrieve" case is not working:

// image upload
var storageRef = firebase.storage().ref('profilePicturesOfAbmin/original/'+file.name);
storageRef.put(file);
function error(err) {
    console.log("error",err);
} 

// retrieve image from firebase storage
var storageRef = firebase.storage().ref();
var spaceRef = storageRef.child('profilePicturesOfAbmin/original/'+file.name);
storageRef.child('profilePicturesOfAbmin/original/'+file.name).getDownloadURL().then(function(url) {
    console.log("bsbdsbsdbd");
    var test = url;
    alert("hfdghjghj",url);
}).catch(function(error) { });

Upvotes: 1

Views: 5375

Answers (3)

Khalid Butt
Khalid Butt

Reputation: 136

var storageRef = firebase.storage().ref('profilePicturesOfAbmin/original/')

storageRef.listAll().then(res => {
    //for folders
    res.perfixes.forEach(folder => {
        console.log(folder);
    });
    // for files NAME and URL
    res.items.forEach(item => {
        // console.log( item.name ); 
        item.getDownloadURL().then(function (url) {
            console.log(url);
        });
    });
})

Upvotes: 0

dawogfather
dawogfather

Reputation: 654

You might want to try something like this...

var storageRef = firebase.storage().ref(filePath);

function uploadImage(event){
  var file = event.target.files[0];

  return storageRef.put(file).then(function(snapshot) {
    // put the file now do something...
    var fullPath = snapshot.metadata.fullPath;
    console.log(fullPath);
  }).catch(function(error){
    console.log("error uploading "+error);
  });
}

function retrieveImage(imageUri, imgElement){
  if (imageUri.startsWith('gs://')) {
    storageRef.refFromURL(imageUri).getMetadata().then(function(metadata) {
      imgElement.src = metadata.downloadURLs[0];
      console.log("URL is "+metadata.downloadURLs[0]);
    }).catch(function(error){
      console.log("error downloading "+error);
    });
  }
}

This will use Promise's to carry out actions once the file has been uploaded successfully.

It will also log to the console when error's occur.

Upvotes: 0

Christopher Rivera
Christopher Rivera

Reputation: 420

So with seeing your error message the idea is todo

StorageRef.put(file, function(){
  // Now do the download
})

Or have a handler that waits till the file is uploaded

Upvotes: 1

Related Questions