在Firebase存储上上传多个图像,然后创建发布

时间:2018-11-11 20:56:01

标签: javascript html html5 firebase firebase-storage

我有一个文件输入,从中我将一系列图像添加到名为var immaginiPost = []的数组中。然后,我想获取所有这些图像并将其添加到Firebase存储中,然后在上传这些图像后,还从其他两个文本输入中获取帖子的标题和内容,并在Firebase数据库上创建一个帖子,在此我还为每个帖子赞扬每个downloadUrl图片。我有一个问题,我需要等待所有图像都已上传到Storage,并且所有downlaodUrls已添加到var immaginiDownloadURL = []数组中,然后才能创建帖子,而我无法弄清楚。预先谢谢你。

    //Here create a new post
function newPost() {
  var postsStorageRef = firebase.storage().ref().child('posts');
  var postDatabaseRef = firebase.database().ref().child('posts');
  var postKey = firebase.database().ref().child('posts').push().key;
  immaginiPost.forEach(function(file){
    let uploadTask = postsStorageRef.child(postKey).child(file.name).put(file);

    uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
      var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case firebase.storage.TaskState.PAUSED: // or 'paused'
          console.log('Upload is paused');
          break;
        case firebase.storage.TaskState.RUNNING: // or 'running'
          console.log('Upload is running');
            break;
      }
    }, function(error) {
  // Handle unsuccessful uploads
  console.log('Unsuccessful upload');
    }, function() {
      // Handle successful uploads on complete
      // For instance, get the download URL: https://firebasestorage.googleapis.com/...
      uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
        console.log('File available at', downloadURL);
        immaginiDownloadUrl.push(downloadURL);
        //Then create the post...
        //TODO: Think of how to add all the pictures and then at the end create the post
      });
    });
  });
};

0 个答案:

没有答案