ウェブで Cloud Storage を使用してファイルを一覧表示する

Cloud Storage for Firebase では、Cloud Storage バケットの内容を一覧表示できます。SDK は現在の Cloud Storage 参照の下にあるアイテム、およびオブジェクトの接頭辞の両方を返します。

List API を使用するプロジェクトには、Cloud Storage for Firebase ルール バージョン 2 が必要です。Firebase プロジェクトがすでに存在する場合は、セキュリティ ルール ガイドの手順に沿って操作してください。

list()Google Cloud Storage List API を使用します。Cloud Storage for Firebase では、ファイル システム セマンティクスをエミュレートするために、区切り文字として / を使用します。大規模な階層型の Cloud Storage バケットを効率的に走査できるようにするために、List API は接頭辞とアイテムを別々に返します。たとえば、1 つのファイル /images/uid/file1 をアップロードすると、次のようになります。

  • root.child('images').listAll() は、接頭辞として /images/uid を返します。
  • root.child('images/uid').listAll() は、ファイルをアイテムとして返します。

Cloud Storage for Firebase SDK は、2 つの連続する / を含む、または /. で終わるオブジェクト パスを返しません。たとえば、次のようなオブジェクトを持つバケットがあるとします。

  • correctPrefix/happyItem
  • wrongPrefix//sadItem
  • lonelyItem/

このバケット内のアイテムのリスト操作によって、次のような結果が得られます。

  • ルートでリスト操作を行うと、correctPrefixwrongPrefixlonelyItem への参照を prefixes として返します。
  • correctPrefix/ でリスト操作を行うと、correctPrefix/happyItem への参照を items として返します。
  • wrongPrefix/ でリスト操作を行うと、wrongPrefix//sadItem に 2 つの連続した / が含まれているため、参照は返されません。
  • lonelyItem/ でリスト操作を行うと、オブジェクト lonelyItem// で終わるため、参照は返されません。

すべてのファイルのリストを取得する

listAll を使用して、ディレクトリのすべての結果をフェッチできます。すべての結果がメモリにバッファされるため、小さなディレクトリに適しています。処理中にオブジェクトが追加または削除された場合は、整合性のあるスナップショットが返されない可能性があります。

listAll() ではすべての結果がメモリにバッファされるため、大きなリストの場合はページ分割に対応した list() メソッドを使用します。

次は listAll の例を示しています。

ウェブ向けのモジュラー API

import { getStorage, ref, listAll } from "firebase/storage";

const storage = getStorage();

// Create a reference under which you want to list
const listRef = ref(storage, 'files/uid');

// Find all the prefixes and items.
listAll(listRef)
  .then((res) => {
    res.prefixes.forEach((folderRef) => {
      // All the prefixes under listRef.
      // You may call listAll() recursively on them.
    });
    res.items.forEach((itemRef) => {
      // All the items under listRef.
    });
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });

ウェブ向けの名前空間付き API

// Create a reference under which you want to list
var listRef = storageRef.child('files/uid');

// Find all the prefixes and items.
listRef.listAll()
  .then((res) => {
    res.prefixes.forEach((folderRef) => {
      // All the prefixes under listRef.
      // You may call listAll() recursively on them.
    });
    res.items.forEach((itemRef) => {
      // All the items under listRef.
    });
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });

リストの結果をページ分割する

list() API では、返される結果の数に制限が設けられます。list() は整合性のあるページビューを提供し、pageToken を公開します。pageToken を使用して、後続の結果をフェッチするタイミングを制御できます。

pageToken には、前の結果で返された最後のアイテムのパスとバージョンがエンコードされます。pageToken を使用した後続のリクエストでは、前回の pageToken の後のアイテムが取り出されます。

次の例は、async/await を使用して結果をページ分割する方法を示します。

ウェブ向けのモジュラー API

import { getStorage, ref, list } from "firebase/storage";

async function pageTokenExample(){
  // Create a reference under which you want to list
  const storage = getStorage();
  const listRef = ref(storage, 'files/uid');

  // Fetch the first page of 100.
  const firstPage = await list(listRef, { maxResults: 100 });

  // Use the result.
  // processItems(firstPage.items)
  // processPrefixes(firstPage.prefixes)

  // Fetch the second page if there are more elements.
  if (firstPage.nextPageToken) {
    const secondPage = await list(listRef, {
      maxResults: 100,
      pageToken: firstPage.nextPageToken,
    });
    // processItems(secondPage.items)
    // processPrefixes(secondPage.prefixes)
  }
}

ウェブ向けの名前空間付き API

async function pageTokenExample(){
  // Create a reference under which you want to list
  var listRef = storageRef.child('files/uid');

  // Fetch the first page of 100.
  var firstPage = await listRef.list({ maxResults: 100});

  // Use the result.
  // processItems(firstPage.items)
  // processPrefixes(firstPage.prefixes)

  // Fetch the second page if there are more elements.
  if (firstPage.nextPageToken) {
    var secondPage = await listRef.list({
      maxResults: 100,
      pageToken: firstPage.nextPageToken,
    });
    // processItems(secondPage.items)
    // processPrefixes(secondPage.prefixes)
  }
}

エラーを処理する

セキュリティ ルールをバージョン 2 にアップグレードしていない場合は、list()listAll() は拒否された Promise を返します。次のエラーが返された場合は、セキュリティ ルールをアップグレードしてください。

Listing objects in a bucket is disallowed for rules_version = "1".
Please update storage security rules to rules_version = "2" to use list.

他にも発生する可能性のあるエラーとして、ユーザーが正しい権限を持っていないことを示すエラーがあります。エラーの詳細については、エラーを処理するのセクションをご覧ください。