如何检查Firebase存储中是否存在文件?

时间:2016-06-10 14:49:05

标签: javascript firebase firebase-storage

使用数据库时,您可以output=0; function addInput(num) { if(accept=="calcText") { if(output=="0") { output=num; } else { output=output+num; } } else if(accept=="new") { output=num; accept="calcText"; } } function type(type) { holder = Number(output); accept = "new"; calcType = type; } function calculate() { if(calcType=="+") { doPlus("+"); } else if(calcType=="-") { doMinus("-"); } else if(calcType=="*") { doPlus(); } else if(calctype=="-") { doMinus(); } else if(calcType=="*") { doTimes(); } else if(calcType=="/") { doDivide(); } } accept="calcText"; on(release, keyPress"+") { function doPlus() { output = holder+Number (output); } type("+"); } on(release, keyPress"-") { function doMinus() { output = holder-Number (output); } type("-"); } on(release,keyPress"/") { function doDivide() { output = holder/Number (output); } type("/"); } on(release,keyPress"*") { function doTimes() { output = holder*Number (output); } type("*"); } stop(); 检查是否存在某些数据。根据文档,没有类似的存储方法。

https://firebase.google.com/docs/reference/js/firebase.storage.Reference

检查Firebase存储中是否存在某个文件的正确方法是什么?

5 个答案:

答案 0 :(得分:13)

您可以使用getDownloadURL返回Promise,而{{3}}又可以用于捕捉"未找到"错误,或处理文件(如果存在)。例如:

storageRef.child("file.png").getDownloadURL().then(onResolve, onReject);

function onResolve(foundURL) {
    //stuff
}

function onReject(error) {
    console.log(error.code);
}

答案 1 :(得分:11)

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");
        }
     })

我分享这个是为了让下一个找到这个帖子的人可以看到它并节省一些时间。

答案 2 :(得分:5)

I believe that the FB storage API is setup in a way that the user only request a file that exists.

Thus a non-existing file will have to be handled as an error: https://firebase.google.com/docs/storage/web/handle-errors

答案 3 :(得分:2)

在使用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 version 5.1.1 (2020-06-19)在撰写本文时

答案 4 :(得分:0)

这对我有用

  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);
  }
相关问题