尝试下载多个文件时如何检查Firebase存储中是否存在文件-javascript

时间:2019-02-25 10:18:35

标签: javascript firebase google-cloud-firestore google-cloud-functions firebase-storage

我有一个需要从Firebase存储下载的文件夹和文件名称的Arrylist。

引发异常,因为其中某些文件夹和文件在Firebase存储中不存在。 这样就不可能在不抛出异常的情况下检测文件夹和文件吗?

JS代码:

var parNum = 'S3DD4';
var sessionNum = '3333';
var storageInfoarr = ["Testing/Testing1.3gp", "Testing/Testing1.xlsx"];
 for (i = 0 ; i< storageInfoarr.length; i++){
    var starsRef = storageRef.child(parNum+'/'+sessionNum+'/'+storageInfoarr[i])
    var urlString = starsRef.getDownloadURL().catch(function(error) {
    switch (error.code) {
      case 'storage/object_not_found': // <<< here you decide what to do when the file doesn't exist
        // File doesn't exist
        break;

      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;

      case 'storage/canceled':
        // User canceled the upload
        break;

    }
  });

1 个答案:

答案 0 :(得分:0)

getDownloadUrl()将始终在路径不正确时抛出异常,您可以做的是处理这些异常,仅下载存在的文件。您可以创建合并的承诺,以告知某些路径正确与不正确,并相应地进行处理。

var parNum = 'S3DD4';
var sessionNum = '3333';
var storageInfoarr = ["Testing/Testing1.3gp", "Testing/Testing1.xlsx"];

Promise.all(storageInfoarr.map((sStorage) => {
    var starsRef = storageRef.child(parNum+'/'+sessionNum+'/'+sStorage);
    starsRef.getDownloadURL().then(url => {
        // url is download url, use it download the file
    }).catch(err => {
       // Here you can handle the error for individual download
    });
}) ).then((aResponses) => {
   // This will be called if all promises are resolved. aResponses contain all download url
}).catch((err) => {
   // This will be called if any of the download path is incorrect, with the error of first promise which fails
});