【问题标题】:Cannot download firebase storage files with js loop无法使用 js 循环下载 Firebase 存储文件
【发布时间】:2020-02-24 09:08:06
【问题描述】:

我正在尝试使用 javascript 循环获取一些 firebase 存储文件的下载 url,如下面的代码所示。它正确地创建了元素,但它只为第二个元素分配了一个“src”(在使用 2 个文件的情况下)。

var photosContainer = document.getElementById('photosContainer');
var photoNumber = firebase.database().ref('main/' + keyParent).child(key + '/number_photos');

photoNumber.on('value', function(snapshot){

  for(var i = 0; i < snapshot.val(); i++){

   var divPhoto = document.createElement('div');
   photosContainer.appendChild(divPhoto);
   var photo = document.createElement('img');
   photo.style.width = '100%';
   divPhoto.appendChild(photo);
   var photosStorage = firebase.storage().ref('main/');
   photosStorage.child(i + key).getDownloadURL().then(function(url) {
      photo.src = url;
   }).catch(function(error) {
     // Handle any errors
     console.log('An error occurred.')
   });
  }
 })

【问题讨论】:

    标签: javascript loops firebase-realtime-database firebase-storage


    【解决方案1】:

    当 getDownloadURL() 从 Firebase 获取文件路径时,“photo.src = url;”是第二个元素Object。

    【讨论】:

    • 知道如何解决吗?
    • 处理异步请求,尝试元素ID:photo.id= 'imgabc-'+i; photosStorage.child(i + key).getDownloadURL().then(function(url) { document.getElementById('imgabc-'+i).src = url; }
    • 它不起作用。我已经在循环中编写了 console.log,在 getDownloadURL().then()... 中编写了另一个,我发现 i 值不一样。它没有按顺序排列。
    【解决方案2】:

    它的工作原理是创建一个数组,将 url 添加到数组中,然后擦除以前的元素并在 array.forEach() 中创建新的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多