在 Android 上使用 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 會分別傳回前置字元和項目。舉例來說,如果您上傳一個檔案 /images/uid/file1

  • root.child('images').listAll() 會傳回 /images/uid 做為前置字串。
  • root.child('images/uid').listAll() 會將檔案做為項目傳回。

Cloud Storage for Firebase SDK 不會傳回含有兩個連續 / 或以 / 結尾的物件路徑。舉例來說,假設某個值區有下列物件:

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

對這個值區中的項目執行清單作業時,會得到下列結果:

  • 根層級的清單作業會傳回 correctPrefixwrongPrefixlonelyItem 的參照,做為 prefixes
  • correctPrefix/ 的清單作業會將 correctPrefix/happyItem 的參照傳回為 items
  • wrongPrefix/ 的清單作業不會傳回任何參照,因為 wrongPrefix//sadItem 包含兩個連續的 /
  • lonelyItem/ 的清單作業不會傳回任何參照,因為物件 lonelyItem/ 會以 / 結尾。

列出所有檔案

您可以使用 listAll 擷取目錄的所有結果。 這項功能最適合小型目錄,因為所有結果都會緩衝處理到記憶體中。 如果在作業期間新增或移除物件,作業也可能無法傳回一致的快照。

如果清單很大,請使用分頁的 list() 方法,因為 listAll() 會將所有結果緩衝處理至記憶體。

以下範例會示範 listAll

Kotlin

val storage = Firebase.storage
val listRef = storage.reference.child("files/uid")

// You'll need to import com.google.firebase.storage.component1 and
// com.google.firebase.storage.component2
listRef.listAll()
    .addOnSuccessListener { (items, prefixes) ->
        for (prefix in prefixes) {
            // All the prefixes under listRef.
            // You may call listAll() recursively on them.
        }

        for (item in items) {
            // All the items under listRef.
        }
    }
    .addOnFailureListener {
        // Uh-oh, an error occurred!
    }

Java

StorageReference listRef = storage.getReference().child("files/uid");

listRef.listAll()
        .addOnSuccessListener(new OnSuccessListener<ListResult>() {
            @Override
            public void onSuccess(ListResult listResult) {
                for (StorageReference prefix : listResult.getPrefixes()) {
                    // All the prefixes under listRef.
                    // You may call listAll() recursively on them.
                }

                for (StorageReference item : listResult.getItems()) {
                    // All the items under listRef.
                }
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Uh-oh, an error occurred!
            }
        });

將清單結果分頁

list() API 會限制傳回的結果數量。list() 提供一致的網頁瀏覽,並公開 pageToken,方便您控制何時要擷取其他結果。

pageToken 會編碼先前結果中傳回的最後一個項目的路徑和版本。在後續使用 pageToken 的要求中,系統會顯示 pageToken 之後的項目。

以下範例說明如何將結果分頁:

Kotlin

fun listAllPaginated(pageToken: String?) {
    val storage = Firebase.storage
    val listRef = storage.reference.child("files/uid")

    // Fetch the next page of results, using the pageToken if we have one.
    val listPageTask = if (pageToken != null) {
        listRef.list(100, pageToken)
    } else {
        listRef.list(100)
    }

    // You'll need to import com.google.firebase.storage.component1 and
    // com.google.firebase.storage.component2
    listPageTask
        .addOnSuccessListener { (items, prefixes, pageToken) ->
            // Process page of results
            processResults(items, prefixes)

            // Recurse onto next page
            pageToken?.let {
                listAllPaginated(it)
            }
        }.addOnFailureListener {
            // Uh-oh, an error occurred.
        }
}

Java

public void listAllPaginated(@Nullable String pageToken) {
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference listRef = storage.getReference().child("files/uid");

    // Fetch the next page of results, using the pageToken if we have one.
    Task<ListResult> listPageTask = pageToken != null
            ? listRef.list(100, pageToken)
            : listRef.list(100);

    listPageTask
            .addOnSuccessListener(new OnSuccessListener<ListResult>() {
                @Override
                public void onSuccess(ListResult listResult) {
                    List<StorageReference> prefixes = listResult.getPrefixes();
                    List<StorageReference> items = listResult.getItems();

                    // Process page of results
                    // ...

                    // Recurse onto next page
                    if (listResult.getPageToken() != null) {
                        listAllPaginated(listResult.getPageToken());
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // Uh-oh, an error occurred.
                }
            });
}

處理錯誤

如果尚未將安全性規則升級至第 2 版,list()listAll() 就會失敗。如果看到以下錯誤,請升級安全性規則:

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

其他可能發生的錯誤可能表示使用者沒有適當的權限。如要進一步瞭解錯誤,請參閱「處理錯誤」。