使用数据库时,您可以snapshot.exists()
检查某些数据是否存在。根据文档,没有类似的存储方法。
https://firebase.google.com/docs/reference/js/firebase.storage.Reference
检查 Firebase 存储中是否存在某个文件的正确方法是什么?
使用数据库时,您可以snapshot.exists()
检查某些数据是否存在。根据文档,没有类似的存储方法。
https://firebase.google.com/docs/reference/js/firebase.storage.Reference
检查 Firebase 存储中是否存在某个文件的正确方法是什么?
您可以使用返回Promise的getDownloadURL ,该 Promise又可用于捕获“未找到”错误,或处理文件(如果存在)。例如:
storageRef.child("file.png").getDownloadURL().then(onResolve, onReject);
function onResolve(foundURL) {
//stuff
}
function onReject(error) {
console.log(error.code);
}
Firebase 添加了一个 .exists() 方法。另一个人回应并提到了这一点,但他们提供的示例代码不正确。我自己在寻找解决方案时发现了这个线程,起初我很困惑,因为我尝试了他们的代码,但即使文件明显不存在,它总是返回“文件存在”。
exists() 返回一个包含布尔值的数组。使用它的正确方法是检查布尔值,如下所示:
const storageFile = bucket.file('path/to/file.txt');
storageFile
.exists()
.then((exists) => {
if (exists[0]) {
console.log("File exists");
} else {
console.log("File does not exist");
}
})
我正在分享这个,以便下一个找到这个帖子的人可以看到它并节省一些时间。
我相信 FB 存储 API 的设置方式是用户只请求存在的文件。
因此,必须将不存在的文件作为错误处理: https ://firebase.google.com/docs/storage/web/handle-errors
我找到了一个很好的解决方案,同时使用File.exists保留在 Node.js Firebase Gogole Cloud Storage SDK 中,告诉它对于那些搜索的人来说是理想的共享。
const admin = require("firebase-admin");
const bucket = admin.storage().bucket('my-bucket');
const storageFile = bucket.file('path/to/file.txt');
storageFile
.exists()
.then(() => {
console.log("File exists");
})
.catch(() => {
console.log("File doesn't exist");
});
Google Cloud Storage:撰写本文时的Node.js SDK 版本 5.1.1 (2020-06-19)
这对我有用
Future<bool> fileExists(String file) async {
var parts = file.split('/');
var path = parts.sublist(0, parts.length - 1).join('/');
var listResult = await _storage.ref().child(path).list();
return listResult.items.any((element) => element.fullPath == file);
}