我正在使用 ionic 3 和 firebase。我正在尝试为每个循环一次上传多个图像。上传它们后,我需要获取下载 url 以将它们存储在数据库中。由于获取“下载 url”部分是异步的,我必须在图像上传的 .then() 部分之后将数据插入到数据库中....我该怎么做?这是我提交表单后到目前为止得到的:
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);
});
})
}
可能对那里的人有用...玩了很长时间后,我想出了一种方法来做到这一点.....首先,我将非图像数据插入到数据库中,例如(标题,内容,类别)。然后我得到插入数据的 key 。然后我用key一张一张的上传图片,会插入图片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);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句