0

我正在使用離子3和firebase。我試圖一次上傳多個圖像使用每個循環。上傳他們之後,我需要獲得下載URL以將它們存儲在數據庫中。由於獲得的「下載URL」部分是異步的,因此我必須在圖像上傳的.then()部分之後將數據插入數據庫....我該如何解決這個問題?這是我走到這一步,在表單提交後:如何發佈多個圖片到firebase並獲得他們的下載url?

post_news(form: NgForm){ 

    this.title = form.value.title; 
    this.content = form.value.content; 
    this.category = form.value.category; 


    console.log(this.capturedimage1); 


    if(this.capturedimage1 !== ''){ 


     this.images_to_upload.push(this.capturedimage1); 


    } 



    if(this.capturedimage2 !== ''){ 

     this.images_to_upload.push(this.capturedimage2); 
    } 

    if(this.capturedimage3 !== ''){ 

     this.images_to_upload.push(this.capturedimage3); 
    } 


    if(this.capturedimage4 !== ''){ 

     this.images_to_upload.push(this.capturedimage4); 
    } 



    images_url_from_db = []; 

    this.images_to_upload.forEach(function(item){ 


     let storageRef = firebase.storage().ref(); 

     const filename = Math.floor(Date.now()/1000); 

     const imageRef = storageRef.child(`images/${filename}.jpg`); 





    imageRef.putString(item, firebase.storage.StringFormat.DATA_URL).then(data=>{ 

    images_url_from_db.push(downloadURL); 



    }); 


    }) 

} 

回答

0

可能是有人在那裏有用......很長一段時間我想出了一個辦法做到這一點後,打第一.....我將非圖像數據插入數據庫,如(標題,內容,類別)。然後我得到插入的數據的關鍵。然後我用這個鍵一個接一個地上傳圖片,這會將image url插入爲image1,image2,image3等......

post_news(form: NgForm){ 

    this.title = form.value.title; 
    this.content = form.value.content; 
    this.category = form.value.category; 


    this.news = this.afDb.list('/news'); 
    this.news.push({title: this.title,content: this.content, category: this.category}).then(data=>{ 

     var item_key = data.key; 

     console.log(data.key); 

     if(this.capturedimage1 !== ''){ 

      let storageRef = firebase.storage().ref(); 

      const filename = Math.floor(Date.now()/1000); 

      const imageRef = storageRef.child(`images/${filename}.jpg`); 


      imageRef.putString(this.capturedimage1, firebase.storage.StringFormat.DATA_URL).then(data=>{ 

      this.news = this.afDb.list('/news'); 
      this.news.update(item_key, {image1: data.downloadURL}); 


      }); 
     } 


     if(this.capturedimage2 !== ''){ 

      let storageRef = firebase.storage().ref(); 

      const filename = 'img'+Math.floor(Date.now()/1000); 

      const imageRef = storageRef.child(`images/${filename}.jpg`); 


      imageRef.putString(this.capturedimage2, firebase.storage.StringFormat.DATA_URL).then(data=>{ 

      this.news = this.afDb.list('/news'); 
      this.news.update(item_key, {image2: data.downloadURL}); 


      }); 
     } 



     }).then(data=>{ 



      form.reset(); 
      this.capturedimage1 = ''; 
      this.capturedimage2 = ''; 
      this.navCtrl.parent.select(0); 

     }); 





} 
相關問題