我正在尝试制作一个简单的网页,只是为了使用 Firebase。我目前正在研究用户上传照片并将其存储以及在数据库中对它们的引用。我有一个工作版本,但唯一的问题是,如果多个用户同时打开页面,则只有最新的帖子会持续。我想使用实时功能来克服这个问题,并想出了这个。
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');
},
);
});
});
这很有效,总是更新 postName 变量,除非当新用户发帖时,它会将每个帖子重写为新帖子。例如,如果用户 A 在用户 B 已经在该页面上时发布了图片,那么当用户 B 发布时,他的帖子将在第一次上传两次,覆盖用户 A 的帖子。谁能解释为什么会发生这种情况?我正在考虑移动监听器来启动该功能,但不确定这是否是正确的选择。
最佳答案
每次检测到新值时,事件监听器都会附加到按钮。这意味着 filebutton
上的 change
事件监听器根本不能位于观察者中。
工作代码:
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');
});
});
关于javascript - Firebase 实时数据库使用 JavaScript 发布旧图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50536733/