Reputation: 3330
I am using ionic 3 and firebase. I am trying to upload multiple images at once using for each loop. After uploading them i need to get the download url to store them in the database. since the getting "download url" part is asynchronous, I have to insert the data into the databse after the .then() part of image uploads....How can I go about this? This is what i got so far after the form is submitted:
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);
});
})
}
Upvotes: 0
Views: 962
Reputation: 3330
Might be useful for someone out there...After playing around a long time I figured out a way to do this.....first I insert the non-image data into the DB like(title,content,category). then I get the inserted data's key . I then use the key to upload the images one by one, which will insert the image url as image1, image2,image3, and so on...
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);
});
}
Upvotes: 1