【问题标题】:react-native: firestore - How to get folder names from storage bucket ref?react-native:firestore - 如何从存储桶引用中获取文件夹名称?
【发布时间】:2020-11-25 06:02:20
【问题描述】:

如果我需要从文件夹中获取图片 url,那么我会执行以下操作:

const ref = storage().ref('foldername');
ref
    .listAll()
    .then(function (result) {
      result.items.forEach(function (imageRef) {
        // And finally display them
        displayImage(imageRef);
      });
    })
    .catch(function (error) {
      console.log(error);
      // Handle any errors
    });

  function displayImage(imageRef) {
    imageRef
      .getDownloadURL()
      .then(function (url) {
        // TODO: Display the image on the UI

        console.log('urlurlurlurl', url);
      })
      .catch(function (error) {
        // Handle any errors
      });
  }

但我需要先获取文件夹名称列表才能在应用程序中显示它们的名称。

例如 - 我的存储桶包含 3 个文件夹。每个文件夹包含 5 张图片。

我需要先获取这 3 个文件夹的列表。

我正在尝试寻找答案here,但找不到。

谢谢

更新: 这是我的带有 2 个目录的存储桶。这两个目录有图像文件

我需要先获取这些目录名称,以便在屏幕上显示它们。然后我会根据客户端的目录选择来获取文件。

【问题讨论】:

    标签: firebase react-native google-cloud-platform firebase-storage react-native-firebase


    【解决方案1】:

    现在,您的代码仅通过迭代 result.items 来查看具有给定前缀的文件:

    ref
        .listAll()
        .then(function (result) {
          result.items.forEach(function (imageRef) {
            // And finally display them
            displayImage(imageRef);
          });
        })
    

    如果您想知道嵌套前缀的名称(您称之为“文件夹”),您还必须迭代 result.prefixes。 React Native 文档似乎没有提供这方面的示例,但您可以在 Firebase docs 中看到它。

    ref
        .listAll()
        .then(function (result) {
          result.items.forEach(function (imageRef) {
            // ...
          });
          result.prefixes.forEach(function (folderRef) {
            // ...
          });
        })
    

    【讨论】:

    • 它显示了前缀的空数组。当我执行 result.prefixes 时,这意味着我必须提供文件夹路径才能获得结果?有没有办法从存储桶中获取所有文件夹名称?
    • 我不知道。我看不到您存储桶中的数据。这是我知道您的代码是否无法按预期工作的唯一方法。
    【解决方案2】:

    我在尝试同样的事情时找到了一种访问文件名的方法:

    使用 refFromURL 创建对 URL 的引用,然后从 URL 引用访问“.name”。

    console.log("FILE NAME" + fileName);

    应该返回您的路径中文件夹中的文件名。

    const getNewImages = () => {
        
        const listRef = storageRef.child("YOUR/PATH");
      
        // Find all the prefixes and items.
        listRef
          .listAll()
          .then((res) => {
        
            
            res.items.forEach((itemRef) => {
              
              let urlRef = storage.refFromURL(itemRef);
              let fileName = urlRef.name;
              console.log("FILE NAME" + fileName);
            });
          })
          .catch((error) => {
            console.log("ERROR" + error);
            // Uh-oh, an error occurred!
          });
      };
    
    

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 2020-04-01
      • 2020-10-30
      • 2021-08-02
      • 2016-06-18
      • 2017-05-06
      • 2020-11-10
      • 1970-01-01
      相关资源
      最近更新 更多