简体   繁体   English

Firebase实时数据库使用JavaScript在旧图像上发布

[英]Firebase real-time database posting over old images with JavaScript

I'm trying to make a simple web page just to play around with Firebase. 我正在尝试制作一个简单的网页,以便与Firebase一起使用。 I'm currently working on users uploading their photos and storing them as well as a reference to them in the database. 我目前正在为用户上传他们的照片并将其存储以及对它们的引用存储在数据库中。 I had a working version except the only issue was that if multiple users opened the page at the same time, only the most recent post would last. 我有一个工作版本,唯一的问题是,如果多个用户同时打开页面,则只有最新的帖子才能持续。 I wanted to use the realtime function to overcome this and have come up with this. 我想使用实时功能来克服这一点,并提出了解决方案。

var postRef = firebase.database().ref('variables/postNumber');
postRef.on('value',function(snapshot) {
    var postName = snapshot.val();
    var uploader = document.getElementById('uploader');
    var filebutton = document.getElementById('filebutton');

    // get file

    filebutton.addEventListener('change', function(e) {
        var file = e.target.files[0];
        var ext = file.name.split('.').pop();;
        console.log(postName);
        console.log(ext);
        //create a storage ref
        var storageRef = firebase.storage().ref('posts/' + postName + "." + ext);

        var task = storageRef.put(file);
        publishPost(postName, ext);
        function publishPost(postName, ext) {
            firebase.database().ref('posts/' + postName).set({
                postID: postName,
                postDate: Date(),
                fileType : ext
            });
            firebase.database().ref('variables/').set({
                postNumber: postName + 1
            });
        }
        task.on('state_changed',

            function progress(snapshot){
                var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
                uploader.value = percentage;
            },
            function error(err){

            },
            function complete(postName, ext){
                uploader.value = 0;
                window.alert('Your meme Uploaded correctly');

            },
        );
    });
});

This works well, always updating the postName variable except when a new user posts, it will rewrite every post to the new post. 这很好用,总是更新postName变量,除非有新用户发布时,它将把每个帖子重写为新帖子。 For example, if user A posts a picture while user B was already on the page, then when user B posts, his post will upload twice the first time overriding user A's post. 例如,如果用户A在用户B已经在页面上时发布了图片,则当用户B发布时,他的帖子将在第一次覆盖用户A的帖子时上传两次。 Can anyone shed some light on why this is happening? 谁能阐明为什么会这样? I was thinking of moving the listener to start the function but not sure if thats the right choice. 我当时在考虑移动监听器来启动该功能,但不确定那是否是正确的选择。

What happens is that the event listener is attached to the button every time new value is detected. 发生的情况是,每次检测到新值时,事件侦听器都将附加到按钮。 Which means that the change event listener on filebutton cannot be in the observer at all. 这意味着filebutton上的change事件侦听器根本不能位于观察器中。

Working code: 工作代码:

let postName = null;

var postRef = firebase.database().ref('variables/postNumber');

postRef.on('value', function(snapshot) {
  const value = snapshot.val();

  if (value === null) {
    // Handle error when no value was returned
    return;
  }

  postName = value;

});

var uploader = document.getElementById('uploader');
var filebutton = document.getElementById('filebutton');

filebutton.addEventListener('change', function(e) {
  if (postName === null) {
    // Handle the case then post name is still null (either wan't loaded yet or couldn't be loaded)
    return;
  }

  var file = e.target.files[0];
  var ext = file.name.split('.').pop();;

  //create a storage ref
  var storageRef = firebase.storage().ref('posts/' + postName + "." + ext);

  var task = storageRef.put(file);
  publishPost(postName, ext);
  function publishPost(postName, ext) {
    firebase.database().ref('posts/' + postName).set({
      postID: postName,
      postDate: Date(),
      fileType : ext
    });
    firebase.database().ref('variables/').set({
      postNumber: postName + 1
    });
  }
  task.on('state_changed', 
  function progress(snapshot){
    var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
    uploader.value = percentage;
  },
  function error(err){

  },
  function complete(postName, ext){
    uploader.value = 0;
    window.alert('Your meme Uploaded correctly');
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM