Skip to content
Advertisement

How do i use a variable in firebase storage ref

I have built a function to get the download URL for the specified ref which can be found below:

function download_file(val) {
 //val = Uploads/Files/swxhlhae-tech-logo.png inside of the function because i have it logged..
 console.log(val)
 var storage = firebase.storage();
 const value = 'Uploads/Files/' + val
                                            
 storage.ref('Uploads/Files/swxhlhae-tech-logo.png').getDownloadURL().then(function(url) {
 
                                            
 console.log(url)
                                            
                                             
 }).catch(function(error) {
  console.log(error)
 });
}

EDIT:

  var databaseRef = firebase.database().ref('Uploads/Files/');
  var rowIndex = 1;
  
  databaseRef.once('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
  var childKey = childSnapshot.key;
  var childData = childSnapshot.val();
  
  
  
  //childKey
  //childData.FirstName
  var html = '<li class="collection-item">';
    html += '<div class="row">';
    html += '<div class="col s9">';
    html += '<p class="collections-title">' + childData.FileName + '</p>';
    html += '<p class="collections-content">' + 'Uploaded: ' + childData.Uploaded + '</p>';
    html += '</div>';
    html += '<div class="col s3">';
    html += '<a href="#" onclick="download_file(this.title)" title=" '+ childData.DownloadName + '">' + '<span class="task-cat blue">Download</span></a>';
    html += '<a href="#" title="' + childKey + '" onclick="delete_file(this.title)"><span id="' + childKey + '" class="task-cat red">Delete</span></a>';
    
    html += '</div>';
    html += '</div>';
    html += '</li>';
    

    document.getElementById('files').innerHTML += html;
    
    
  
    });
  });

EDIT : This code above this generates html, i made it so it makes a title on the button, when clicked it grabs the buttons title value, and then it passes that (val) variable to that function above, and then goes from there

And Basically when i use the example above it wrks just fine… but when i use a variable called (value) it tells me that there is a 404 file doesnt exist… but when i look at the (value) variable and the original ref that i typed into the function… there the exact same why isnt it working? Why cant i use the variable?

Advertisement

Answer

The problem is that this.tile in onclick="download_file(this.title)" is evaluated when the user clicks the element, and at that point this is a different object. The easiest way to fix this is to inject the correct value into the childData.DownloadName immediately when you render the HTML:

html += `<a href="#" onclick="download_file('${childData.DownloadName}')" title="${childData.DownloadName}"><span class="task-cat blue">Download</span></a>`;
Advertisement