Listar objetos

Esta página mostra-lhe como listar os objetos armazenados nos seus contentores do Cloud Storage, que estão ordenados lexicograficamente por nome na lista.

Antes de começar

Para receber as autorizações necessárias para listar objetos, peça ao seu administrador para lhe conceder a função de IAM (roles/storage.objectViewer) de leitor de objetos de armazenamento para o contentor que contém os objetos que quer listar. Se quiser listar objetos em pastas geridas, pode conceder roles/storage.objectViewer na pasta gerida que contém os objetos que quer ver em vez do contentor.

Se planeia usar a Google Cloud consola para realizar as tarefas nesta página, peça ao seu administrador que lhe conceda a função básica de leitor (roles/viewer) além da função de leitor de objetos de armazenamento (roles/storage.objectViewer).

Estas funções contêm as autorizações necessárias para listar objetos. Para ver as autorizações exatas necessárias, expanda a secção Autorizações necessárias:

Autorizações necessárias

  • storage.objects.list
  • storage.buckets.list
    • Esta autorização só é necessária se quiser usar a Google Cloud consola para realizar as tarefas nesta página.

Também pode obter estas autorizações com outras funções predefinidas ou funções personalizadas.

Para ver informações sobre a concessão de funções para contentores, consulte o artigo Use o IAM com contentores.

Indique os objetos num contentor

Consola

  1. Na Google Cloud consola, aceda à página Recipientes do Cloud Storage.

    Aceda a Recipientes

  2. Na lista de contentores, clique no nome do contentor cujo conteúdo quer ver.

Linha de comandos

Use o comando gcloud storage ls:

gcloud storage ls gs://BUCKET_NAME

Onde:

  • BUCKET_NAME é o nome do contentor que contém os objetos que quer listar. Por exemplo, my-bucket.

Bibliotecas cliente

C++

Para mais informações, consulte a documentação de referência da API C++ do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name) {
  for (auto&& object_metadata : client.ListObjects(bucket_name)) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name() << "\n";
  }
}

O exemplo seguinte lista objetos com um prefixo determinado:

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& bucket_prefix) {
  for (auto&& object_metadata :
       client.ListObjects(bucket_name, gcs::Prefix(bucket_prefix))) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name() << "\n";
  }
}

C#

Para mais informações, consulte a documentação de referência da API C# do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:


using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ListFilesSample
{
    public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFiles(
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var storageObjects = storage.ListObjects(bucketName);
        Console.WriteLine($"Files in bucket {bucketName}:");
        foreach (var storageObject in storageObjects)
        {
            Console.WriteLine(storageObject.Name);
        }

        return storageObjects;
    }
}

O exemplo seguinte lista objetos com um prefixo determinado:


using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ListFilesWithPrefixSample
{
    /// <summary>
    /// Prefixes and delimiters can be used to emulate directory listings.
    /// Prefixes can be used to filter objects starting with prefix.
    /// The delimiter argument can be used to restrict the results to only the
    /// objects in the given "directory". Without the delimiter, the entire  tree
    /// under the prefix is returned.
    /// For example, given these objects:
    ///   a/1.txt
    ///   a/b/2.txt
    ///
    /// If you just specify prefix="a/", you'll get back:
    ///   a/1.txt
    ///   a/b/2.txt
    ///
    /// However, if you specify prefix="a/" and delimiter="/", you'll get back:
    ///   a/1.txt
    /// </summary>
    /// <param name="bucketName">The bucket to list the objects from.</param>
    /// <param name="prefix">The prefix to match. Only objects with names that start with this string will
    /// be returned. This parameter may be null or empty, in which case no filtering
    /// is performed.</param>
    /// <param name="delimiter">Used to list in "directory mode". Only objects whose names (aside from the prefix)
    /// do not contain the delimiter will be returned.</param>
    public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFilesWithPrefix(
        string bucketName = "your-unique-bucket-name",
        string prefix = "your-prefix",
        string delimiter = "your-delimiter")
    {
        var storage = StorageClient.Create();
        var options = new ListObjectsOptions { Delimiter = delimiter };
        var storageObjects = storage.ListObjects(bucketName, prefix, options);
        Console.WriteLine($"Objects in bucket {bucketName} with prefix {prefix}:");
        foreach (var storageObject in storageObjects)
        {
            Console.WriteLine(storageObject.Name);
        }
        return storageObjects;
    }
}

Go

Para mais informações, consulte a documentação de referência da API Go do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFiles lists objects within specified bucket.
func listFiles(w io.Writer, bucket string) error {
	// bucket := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	it := client.Bucket(bucket).Objects(ctx, nil)
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects: %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name)
	}
	return nil
}

O exemplo seguinte lista objetos com um prefixo determinado:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFilesWithPrefix lists objects using prefix and delimeter.
func listFilesWithPrefix(w io.Writer, bucket, prefix, delim string) error {
	// bucket := "bucket-name"
	// prefix := "/foo"
	// delim := "_"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	// Prefixes and delimiters can be used to emulate directory listings.
	// Prefixes can be used to filter objects starting with prefix.
	// The delimiter argument can be used to restrict the results to only the
	// objects in the given "directory". Without the delimiter, the entire tree
	// under the prefix is returned.
	//
	// For example, given these blobs:
	//   /a/1.txt
	//   /a/b/2.txt
	//
	// If you just specify prefix="a/", you'll get back:
	//   /a/1.txt
	//   /a/b/2.txt
	//
	// However, if you specify prefix="a/" and delim="/", you'll get back:
	//   /a/1.txt
	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	it := client.Bucket(bucket).Objects(ctx, &storage.Query{
		Prefix:    prefix,
		Delimiter: delim,
	})
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects(): %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name)
	}
	return nil
}

Java

Para mais informações, consulte a documentação de referência da API Java do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjects {
  public static void listObjects(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Page<Blob> blobs = storage.list(bucketName);

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
    }
  }
}

O exemplo seguinte lista objetos com um prefixo determinado:

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjectsWithPrefix {
  public static void listObjectsWithPrefix(
      String projectId, String bucketName, String directoryPrefix) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The directory prefix to search for
    // String directoryPrefix = "myDirectory/"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    /**
     * Using the Storage.BlobListOption.currentDirectory() option here causes the results to display
     * in a "directory-like" mode, showing what objects are in the directory you've specified, as
     * well as what other directories exist in that directory. For example, given these blobs:
     *
     * <p>a/1.txt a/b/2.txt a/b/3.txt
     *
     * <p>If you specify prefix = "a/" and don't use Storage.BlobListOption.currentDirectory(),
     * you'll get back:
     *
     * <p>a/1.txt a/b/2.txt a/b/3.txt
     *
     * <p>However, if you specify prefix = "a/" and do use
     * Storage.BlobListOption.currentDirectory(), you'll get back:
     *
     * <p>a/1.txt a/b/
     *
     * <p>Because a/1.txt is the only file in the a/ directory and a/b/ is a directory inside the
     * /a/ directory.
     */
    Page<Blob> blobs =
        storage.list(
            bucketName,
            Storage.BlobListOption.prefix(directoryPrefix),
            Storage.BlobListOption.currentDirectory());

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
    }
  }
}

Node.js

Para mais informações, consulte a documentação de referência da API Node.js do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFiles() {
  // Lists files in the bucket
  const [files] = await storage.bucket(bucketName).getFiles();

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFiles().catch(console.error);

O exemplo seguinte lista objetos com um prefixo determinado:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The directory prefix to search for
// const prefix = 'myDirectory/';

// The delimiter to use
// const delimiter = '/';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFilesByPrefix() {
  /**
   * This can be used to list all blobs in a "folder", e.g. "public/".
   *
   * The delimiter argument can be used to restrict the results to only the
   * "files" in the given "folder". Without the delimiter, the entire tree under
   * the prefix is returned. For example, given these blobs:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * If you just specify prefix = 'a/', you'll get back:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * However, if you specify prefix='a/' and delimiter='/', you'll get back:
   *
   *   /a/1.txt
   */
  const options = {
    prefix: prefix,
  };

  if (delimiter) {
    options.delimiter = delimiter;
  }

  // Lists files in the bucket, filtered by a prefix
  const [files] = await storage.bucket(bucketName).getFiles(options);

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFilesByPrefix().catch(console.error);

PHP

Para mais informações, consulte a documentação de referência da API PHP do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_objects(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    foreach ($bucket->objects() as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

O exemplo seguinte lista objetos com um prefixo determinado:

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects with specified prefix.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $directoryPrefix the prefix to use in the list objects API call.
 *        (e.g. 'myDirectory/')
 */
function list_objects_with_prefix(string $bucketName, string $directoryPrefix): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $options = ['prefix' => $directoryPrefix];
    foreach ($bucket->objects($options) as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

Python

Para mais informações, consulte a documentação de referência da API Python do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:

from google.cloud import storage


def list_blobs(bucket_name):
    """Lists all the blobs in the bucket."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(bucket_name)

    # Note: The call returns a response only when the iterator is consumed.
    for blob in blobs:
        print(blob.name)

O exemplo seguinte lista objetos com um prefixo determinado:

from google.cloud import storage


def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):
    """Lists all the blobs in the bucket that begin with the prefix.

    This can be used to list all blobs in a "folder", e.g. "public/".

    The delimiter argument can be used to restrict the results to only the
    "files" in the given "folder". Without the delimiter, the entire tree under
    the prefix is returned. For example, given these blobs:

        a/1.txt
        a/b/2.txt

    If you specify prefix ='a/', without a delimiter, you'll get back:

        a/1.txt
        a/b/2.txt

    However, if you specify prefix='a/' and delimiter='/', you'll get back
    only the file directly under 'a/':

        a/1.txt

    As part of the response, you'll also get back a blobs.prefixes entity
    that lists the "subfolders" under `a/`:

        a/b/


    Note: If you only want to list prefixes a/b/ and don't want to iterate over
    blobs, you can do

    ```
    for page in blobs.pages:
        print(page.prefixes)
    ```
    """

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(
        bucket_name, prefix=prefix, delimiter=delimiter
    )

    # Note: The call returns a response only when the iterator is consumed.
    print("Blobs:")
    for blob in blobs:
        print(blob.name)

    if delimiter:
        print("Prefixes:")
        for prefix in blobs.prefixes:
            print(prefix)

Ruby

Para mais informações, consulte a documentação de referência da API Ruby do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte lista todos os objetos num contentor:

def list_files bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.files.each do |file|
    puts file.name
  end
end

O exemplo seguinte lista objetos com um prefixo determinado:

def list_files_with_prefix bucket_name:, prefix:, delimiter: nil
  # Lists all the files in the bucket that begin with the prefix.
  #
  # This can be used to list all files in a "folder", e.g. "public/".
  #
  # The delimiter argument can be used to restrict the results to only the
  # "files" in the given "folder". Without the delimiter, the entire tree under
  # the prefix is returned. For example, given these files:
  #
  #     a/1.txt
  #     a/b/2.txt
  #
  # If you just specify `prefix: "a"`, you will get back:
  #
  #     a/1.txt
  #     a/b/2.txt
  #
  # However, if you specify `prefix: "a"` and `delimiter: "/"`, you will get back:
  #
  #     a/1.txt

  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The directory prefix to search for
  # prefix = "a"

  # The delimiter to be used to restrict the results
  # delimiter = "/"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  files   = bucket.files prefix: prefix, delimiter: delimiter

  files.each do |file|
    puts file.name
  end
end

APIs REST

API JSON

  1. Ter a CLI gcloud instalada e inicializada, o que lhe permite gerar um token de acesso para o cabeçalho Authorization.

  2. Use cURL para chamar a API JSON com um pedido para listar objetos:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"

    Em que BUCKET_NAME é o nome do contentor cujos objetos quer listar. Por exemplo, my-bucket.

API XML

  1. Ter a CLI gcloud instalada e inicializada, o que lhe permite gerar um token de acesso para o cabeçalho Authorization.

  2. Use cURLpara chamar a API XML com um pedido de GET contentor:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?list-type=2"

    Em que BUCKET_NAME é o nome do contentor cujos objetos quer listar. Por exemplo, my-bucket.

    Pode usar um parâmetro de prefix=PREFIXstring de consulta para limitar os resultados a objetos que tenham o prefixo especificado.

Indicar os objetos numa pasta

Consola

  1. Na Google Cloud consola, aceda à página Recipientes do Cloud Storage.

    Aceda a Recipientes

  2. Na lista de contentores, clique no nome do contentor que contém a pasta.

  3. No separador Objetos da página Detalhes do contentor, clique no nome da pasta cujo conteúdo quer ver.

Linha de comandos

Use o comando gcloud storage ls para listar os objetos numa pasta:

gcloud storage ls gs://BUCKET_NAME/FOLDER_NAME

Onde:

  • BUCKET_NAME é o nome do contentor que contém a pasta. Por exemplo, my-bucket.

  • FOLDER_NAME é o nome da pasta que contém os objetos que quer listar. Por exemplo, my-folder.

APIs REST

API JSON

Para listar os objetos numa pasta, use um pedido de objetos de lista com os parâmetros prefix e delimiter. Quando o parâmetro prefix está definido, a operação de listagem tem âmbito apenas para devolver objetos e pastas no prefixo. Quando o parâmetro delimiter está definido, a lista prefixes[] na resposta é preenchida com os nomes das pastas no prefixo especificado.

Por exemplo:

  • Para listar todos os objetos na pasta image/ no contentor my-bucket, use o seguinte URL: "https://storage.googleapis.com/storage/v1/b/my-bucket/o?prefix=image&delimiter=/".

    Isto pode devolver os objetos my-bucket/image/cat.jpeg e my-bucket/image/dog.jpeg.

  • Para incluir objetos em subpastas dentro de image/, remova o parâmetro delimiter: "https://storage.googleapis.com/storage/v1/b/my-bucket/o?prefix=image".

    Isto pode devolver os objetos my-bucket/image/cat.jpeg, my-bucket/image/dog.jpeg e my-bucket/image/dog/shiba.jpeg.

Para usar carateres universais no seu pedido de objetos de lista e fazer corresponder objetos por expressão glob, use o parâmetro matchGlob. Por exemplo, matchGlob=**.jpeg corresponde a todos os objetos que terminam em .jpeg. Quando usa matchGlob, tem de definir delimiter como /.

Por exemplo, use o seguinte URL para fazer corresponder todos os objetos na pasta image que terminam em .jpeg: "https://storage.googleapis.com/storage/v1/b/my-bucket/o?prefix=image&delimiter=/&matchGlob=**.jpeg"

Para ver mais detalhes sobre a utilização de parâmetros para filtrar objetos, consulte a documentação de referência da API JSON da lista de objetos.

Exemplo de utilização

A utilização de prefix para listar o conteúdo de uma pasta pode ser útil quando só tem autorização para listar objetos na pasta, mas não no contentor completo. Por exemplo, suponhamos que tem a função do IAM (roles/storage.objectViewer) Storage Object Viewer para a pasta gerida my-bucket/my-managed-folder-a/, mas não para a pasta gerida my-bucket/my-managed-folder-b/. Para devolver apenas os objetos em my-managed-folder-a, pode especificar prefix=my-managed-folder-a/.

Filtrar objetos

Quando listar objetos, pode usar prefixos ou sufixos no pedido de lista para filtrar objetos por nome.

Consola

Consulte a secção sobre filtragem e ordenação para obter informações sobre como filtrar e ordenar objetos em contentores ou pastas.

Linha de comandos

Pode usar carateres universais no comando gcloud storage ls para filtrar objetos por prefixo ou sufixo. Por exemplo, o comando seguinte apenas lista objetos no contentor my-bucket cujo nome começa com image e termina com .png:

gcloud storage ls gs://my-bucket/image*.png

Se o pedido for bem-sucedido, a resposta é semelhante à seguinte:

gs://my-bucket/image.png
gs://my-bucket/image-dog.png
gs://my-bucket/image-cat.png
...

Pode usar carateres universais com dois asteriscos para estabelecer uma correspondência com zero ou mais níveis de pastas num caminho. Por exemplo, o comando seguinte apenas lista objetos cujo nome termina em .jpeg em qualquer pasta ou subpasta no contentor my-bucket:

gcloud storage ls gs://my-bucket/**/*.jpeg

Se o pedido for bem-sucedido, a resposta é semelhante à seguinte:

gs://my-bucket/puppy.jpeg
gs://my-bucket/pug.jpeg
gs://my-bucket/pets/dog.jpeg
...

APIs REST

Consulte o artigo Liste objetos em pastas para obter informações sobre como filtrar objetos por pasta ou prefixo do nome do objeto.

Considerações de desempenho ao listar objetos

A estrutura subjacente dos contentores com o espaço de nomes hierárquico ativado influencia o desempenho da operação de objetos de listagem, quando comparada com contentores de espaço de nomes simples. Para mais informações, consulte o artigo Otimize o desempenho em contentores com o espaço de nomes hierárquico ativado.

O que se segue?