Web'de Cloud Storage ile dosyaları listeleme

Cloud Storage for Firebase, Cloud Storage paketinizin içeriğini listelemenize olanak tanır. SDK'lar, geçerli Cloud Storage referansı altında hem öğeleri hem de nesnelerin ön eklerinin döndürür.

List API'yi kullanan projeler için Cloud Storage for Firebase Kurallar 2 sürümü gerekir. Mevcut bir Firebase projeniz varsa Güvenlik Kuralları Kılavuzu'ndaki adımları uygulayın.

list(), Google Cloud Storage List API'yi kullanır. Cloud Storage for Firebase dosyasında, dosya sistemi anlamlarını taklit etmemizi sağlayan bir ayırıcı olarak / kullanılır. List API, büyük ve hiyerarşik Cloud Storage paketlerin verimli bir şekilde taranmasına olanak tanımak için ön ekleri ve öğeleri ayrı ayrı döndürür. Örneğin, bir dosya /images/uid/file1 yüklerseniz

  • root.child('images').listAll(), ön ek olarak /images/uid değerini döndürür.
  • root.child('images/uid').listAll(), dosyayı öğe olarak döndürür.

Cloud Storage for Firebase SDK'sı, art arda iki / içeren veya /. ile biten nesne yolları döndürmez. Örneğin, aşağıdaki nesneleri içeren bir paketi ele alalım:

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

Bu paketteki öğelerle ilgili liste işlemleri aşağıdaki sonuçları verir:

  • Kökteki liste işlemi, correctPrefix, wrongPrefix ve lonelyItem referanslarını prefixes olarak döndürür.
  • correctPrefix/'teki liste işlemi, correctPrefix/happyItem'a yapılan referansları items olarak döndürür.
  • wrongPrefix//sadItem, art arda iki / içerdiğinden wrongPrefix/'teki liste işlemi hiçbir referans döndürmez.
  • lonelyItem/ nesnesi / ile bittiği için lonelyItem/ adresindeki liste işlemi hiçbir referans döndürmez.

Tüm dosyaları listeleme

Bir dizinle ilgili tüm sonuçları almak için listAll değerini kullanabilirsiniz. Tüm sonuçlar bellekte arabelleğe alındığından bu yöntem küçük dizinler için en iyi şekilde kullanılır. İşlem sırasında nesne eklenir veya kaldırılırsa işlem tutarlı bir anlık görüntü döndürmeyebilir.

Büyük bir liste için sayfalandırılmış list() yöntemini kullanın. listAll(), tüm sonuçları bellekte arabelleğe alır.

Aşağıdaki örnekte listAll gösterilmektedir.

Web

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

Web

// 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!
  });

Liste sonuçlarını sayfalara ayırma

list() API, döndürdüğü sonuç sayısına bir sınır uygular. list(), tutarlı bir sayfa görüntüleme sağlar ve ek sonuçların ne zaman getirileceğini kontrol etmenize olanak tanıyan bir pageToken gösterir.

pageToken, önceki sonuçta döndürülen son öğenin yolunu ve sürümünü kodlar. pageToken'un kullanıldığı bir sonraki istekte, pageToken'dan sonra gelen öğeler gösterilir.

Aşağıdaki örnekte, async/await kullanılarak bir sonucun sayfalara bölünmesi gösterilmektedir.

Web

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

Web

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

Hataları işleme

Güvenlik kurallarını 2. sürüme yükseltmediyseniz list() ve listAll(), reddedilen bir Promise döndürür. Aşağıdaki hatayı görüyorsanız güvenlik kurallarınızı yükseltin:

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

Olası diğer hatalar, kullanıcının doğru izne sahip olmadığını gösterebilir. Hatalarla ilgili daha fazla bilgiyi Hataları ele alma bölümünde bulabilirsiniz.