【发布时间】:2020-01-04 07:24:19
【问题描述】:
所以我需要将文档保存到我的 Firestore,每个文档都有一个文件链接(下载链接)。
为了实现这一点,我:
- 将文件上传到 Firebase 存储
- 上传成功后获取文件的下载链接。
- 使用链接到存储文件的 download_url 字段上传文档。
您可以在代码中看到这一点。
这有以下问题:
- 我的 JavaScript 都是客户端的(我使用 Github Pages),因此有人可以简单地更改下载链接并将其放入文档上传中。
我可以添加检查下载链接是否以https://firebasestorage.googleapis.com/v0/b/my_application.appspot.com/o/info 开头的firestore 规则,但这真的是最好的方法吗? - 如果要上传的文件是合法的,但文件不合法,文件将保存到我的存储中,但文件将被拒绝。没有参考文件,除非我手动删除它,否则它将始终保留在我的存储空间中。
function uploadFile(my_file) {
// Create a root reference
var storageRef = firebase.storage().ref();
var uploadTask = storageRef.child('info/' + my_file.name).put(my_file);
uploadTask.on('state_changed', function (snapshot) {
}, function (error) {
console.error("Error uploading file: ", error);
}, function () {
// Handle successful uploads on complete
uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
uploadDocument(downloadURL);
});
});
}
function uploadDocument(downloadUrl) {
var name = document.forms["infoForm"]["name"].value;
var author = document.forms["infoForm"]["author"].value;
var documentObject = {
name: name,
author: author,
download_url: downloadUrl
};
db.collection("info").add(documentObject)
.then(function (docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function (error) {
console.error("Error adding document: ", error);
});
}
我不知道处理这个问题的最佳方法是什么。任何帮助将不胜感激:)
【问题讨论】:
-
请限制自己在每个帖子中回答一个问题。请注意,第二个问题之前已解决,通常意味着您需要运行定期进程来清理孤立文件。
-
抱歉,在写这篇文章时,我意识到我目前的方法还有另一个问题 :)
标签: javascript firebase google-cloud-firestore firebase-storage github-pages