Listar objetos

Nesta página, veja como listar os objetos armazenados nos buckets do Cloud Storage, que são ordenados na lista de maneira lexicográfica pelo nome.

Antes de começar

Para receber as permissões necessárias para listar objetos, peça ao administrador que conceda a você o papel do IAM de Leitor de objetos do Storage (roles/storage.objectViewer) para o bucket que contém os objetos que você quer listar.

Se você quiser retornar Access Control Lists de objetos como parte da solicitação ou usar o console do Google Cloud para executar as tarefas desta página, você precisará de papéis alternativos:

  • Se você quiser retornar ACLs de objetos como parte de sua solicitação, peça ao administrador para conceder a você o papel Administrador de objetos do Storage (roles/storage.objectAdmin) em vez do papel de Leitor de objetos do Storage (roles/storage.objectViewer).

  • Se você planeja usar o console do Google Cloud para executar as tarefas nesta página, peça ao administrador para conceder a você o papel Administrador do Storage (roles/storage.admin) em vez do Leitor de objetos do Storage (roles/storage.objectViewer).

    Outra possibilidade é pedir ao administrador para conceder a você o papel básico de Leitor (roles/viewer), além do papel de Leitor de objetos do Storage (roles/storage.objectViewer).

Esses papéis contêm as permissões necessárias para listar objetos. Para ver as permissões exatas necessárias, expanda a seção Permissões necessárias:

Permissões necessárias

  • storage.objects.list
  • storage.objects.getIamPolicy
    • Essa permissão só será necessária se você quiser retornar Access Control Lists de objetos
  • storage.buckets.list
    • Essa permissão só será necessária se você quiser usar o console do Google Cloud para executar as tarefas desta página.

Também é possível conseguir essas permissões com outros papéis predefinidos ou personalizados.

Para informações sobre como conceder papéis para buckets, consulte Usar o IAM com buckets.

Listar os objetos em um bucket

Siga estas etapas para listar os objetos em um bucket:

Console

  1. No Console do Google Cloud, acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Na lista de buckets, clique no nome do bucket cujo conteúdo você quer visualizar.

  3. Opcional: use a filtragem e a classificação para limitar e organizar os resultados na sua lista.

Linha de comando

Use o comando gcloud storage ls com a flag --recursive:

gcloud storage ls --recursive gs://BUCKET_NAME/**

Em que:

  • BUCKET_NAME é o nome do bucket cujos objetos você quer listar. Por exemplo, my-bucket.

A resposta terá esta aparência:

gs://my-bucket/cats.jpeg
gs://my-bucket/dogs.jpeg
gs://my-bucket/thesis.txt
...

Bibliotecas de cliente

C++

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

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:

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";
  }
}

A amostra a seguir lista os 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 Cloud Storage C#.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:


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

A amostra a seguir lista os 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 Cloud Storage Go.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:

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
}

A amostra a seguir lista os 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 Cloud Storage Java.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:

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

A amostra a seguir lista os 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 Cloud Storage Node.js.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:

/**
 * 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);

A amostra a seguir lista os 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 Cloud Storage PHP.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:

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

A amostra a seguir lista os 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 Cloud Storage Python.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:

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)

A amostra a seguir lista os 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/
    """

    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 Cloud Storage Ruby.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir lista todos os objetos de um bucket:

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

A amostra a seguir lista os 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 gcloud CLI instalada e inicializadapara gerar um token de acesso para o cabeçalho Authorization.

    Como alternativa, é possível criar um token de acesso usando o OAuth 2.0 Playground e incluí-lo no cabeçalho Authorization.

  2. Use cURL para chamar a API JSON com uma solicitação 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 bucket com os objetos que você quer listar. Por exemplo, my-bucket.

    Use o parâmetro de consulta includeFoldersAsPrefixes=True para retornar pastas gerenciadas como parte dos resultados da lista. Ao usar o parâmetro includeFoldersAsPrefixes, o parâmetro delimiter precisa ser definido como /.

    Para retornar ACLs de objeto, anexe o parâmetro de consulta projection com o valor full à sua solicitação. As ACLs serão desativadas e não poderão ser retornadas se o acesso uniforme no nível do bucket estiver ativado no bucket.

API XML

  1. Ter a gcloud CLI instalada e inicializadapara gerar um token de acesso para o cabeçalho Authorization.

    Como alternativa, é possível criar um token de acesso usando o OAuth 2.0 Playground e incluí-lo no cabeçalho Authorization.

  2. Use cURL para chamar a API XML com uma solicitação GET bucket:

    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 bucket com os objetos que você quer listar. Por exemplo, my-bucket.

    É possível usar um parâmetro de string de consulta prefix=PREFIX para limitar os resultados a objetos que tenham o prefixo especificado.

Como filtrar objetos

Console

Para filtrar objetos pelo prefixo de nome usando o Console do Google Cloud, use o campo Filtrar objetos e pastas na página Detalhes do bucket.

Consulte Como filtrar e classificar para conferir outras opções de filtragem disponíveis usando o console do Google Cloud.

Linha de comando

Ao listar objetos usando a CLI do Google Cloud, é possível usar caracteres curinga para filtrar objetos que começam com um prefixo especificado ou terminam com um sufixo especificado. Por exemplo, o comando a seguir corresponde a objetos .png que começam com image:

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

Para mais informações sobre filtragem usando a CLI do Google Cloud, consulte a documentação do gcloud storage ls.

APIs REST

API JSON

Ao listar objetos usando a API Cloud Storage JSON, use os parâmetros de string de consulta prefix ou matchGlob para filtrar os resultados. Para saber como usar esses parâmetros de string de consulta, confira a documentação de referência da API JSON com relação à lista de objetos.

Como fazer a filtragem por prefixo

Use prefix=PREFIX ou o parâmetro de string de consulta para limitar os resultados a objetos ou pastas gerenciadas que tenham o prefixo especificado. Por exemplo, para listar todos os objetos no bucket my-bucket com o prefixo folder/subfolder/, faça uma solicitação de listagem de objetos usando o URL "https://storage.googleapis.com/storage/v1/b/my-bucket?prefix=folder/subfolder/":

O uso de prefix para listar o conteúdo de uma pasta gerenciada é útil quando você só tem permissão para listar objetos nela, não no bucket inteiro. Por exemplo, digamos que você tenha o papel do IAM de Leitor de objetos do Storage (roles/storage.objectViewer) para a pasta gerenciada my-bucket/my-managed-folder-a/, mas não para a pasta gerenciada my-bucket/my-managed-folder-b/. Para retornar apenas os objetos em my-managed-folder-a, especifique prefix=my-managed-folder-a/.

Ao limitar os resultados a uma pasta gerenciada e aos objetos nela, você precisa terminar PREFIX com / (por exemplo, prefix=my-managed-folder/). Caso contrário, os resultados também podem incluir objetos adjacentes à pasta gerenciada. Neste exemplo, você tem um bucket que contém os seguintes objetos:

  • my-bucket/abc.txt
  • my-bucket/abc/object.txt

Especificar prefix=abc/ pode retornar os objetos my-bucket/abc/object.txt, enquanto especificar prefix=abc pode retornar my-bucket/abc.txt e my-bucket/abc/object.txt.

Como fazer a filtragem por expressão glob

Use o parâmetro de string de consulta matchGlob=GLOB_PATTERN a fim de filtrar os resultados apenas para os objetos que correspondem a uma expressão glob específica. Por exemplo, matchGlob=**.jpeg pode ser usado para corresponder a todos os objetos cujos nomes terminam com .jpeg.

As solicitações que usam o parâmetro matchGlob falharão se também incluírem um parâmetro delimiter definido com um valor diferente de /.

A seguir