Firebase web record url in database after uploading file to storage

0

Maybe someone can help me with this code I am trying to record information in the database of firebase after I upload a file to storage but it does not record just upload the file and what I want is that it also saves the url and the name of the file in database

window.onload = inicializar;

var fichero;
var storageRef;
var imagenesFBRef;

function inicializar() {
  fichero = document.getElementById("fichero");
  fichero.addEventListener("change",subirImagenAFirebase, false);
  storageRef = firebase.storage().ref();
  imagenesFBRef=firebase.database().ref().child("imagenesFB");


mostrarImagenesDeFirebase();

}
function mostrarImagenesDeFirebase(){
imagenesFBRef.on("value",function(snapshot){
var datos = snapshot.val();
var result="";
for (var key in datos){
  result +='<img width=200 class="img-thumbnail" src="'+datos[key].url+'"/>';
}
document.getElementById("imagenes-de-firebase").innerHTML=result;
})
}
function subirImagenAFirebase(){
var imagenASubir = fichero.files[0];
// Upload the file and metadata
var uploadTask = storageRef.child('images/' + imagenASubir.name).put(imagenASubir);
  document.getElementById("progreso").className="";

  uploadTask.on('state_changed',
  function(snapshot){
var barraProgreso = (snapshot.bytesTransferred / snapshot.totalBytes)*100;
document.getElementById("barra-de-progreso").style.width = barraProgreso + "%";
  }, function(error) {

    // Handle unsuccessful uploads
  }, function() {

    // Handle successful uploads on complete
    // For instance, get the download URL: https://firebasestorage.googleapis.com/...
    var downloadURL= uploadTask.snapshot.downloadURL;

firebase.database().ref().child('imagenesFB').push({nombre:imagenASubir.name, url:downloadURL});
    crearNodoEnBDFirebase(imagenASubir.name,downloadURL);

    document.getElementById("progreso").className="hidden";

    });

  function crearNodoEnBDFirebase(nombreImagen,downloadURL)  {
//firebase.database().ref('imagenesFB').push({nombre:nombreImagen, url:downloadURL});
imagenesFBRef.push({nombre:nombreImagen, url:downloadURL});

}
}
    
asked by Jorge Toledo 23.07.2018 в 14:01
source

1 answer

0

At first glance I see that you are not handling the case of successful upload, that's why your logic is not executed. According to the documentation you should implement the upload as:

ref.put(archivo).then(function(snapshot) {
  <!-- hacer algo acá -->
});

The code is messy but I think you are only handling STATE_CHANGED but not the full upload. Could you confirm if you get to run the load section in the base of Firebase?

As a comment I suggest you see the section of Firebase functions , as it has an example very similar to what you want to do and could help you automate this logic.

    
answered by 23.07.2018 в 21:18