列出对象

本页面介绍如何列出 Cloud Storage 存储分区中存储的对象,这些对象在列表中按名称的字典顺序排序。如需查看存储分区和对象的概览,请参阅关键术语

要列出存储分区中的对象,请执行以下操作:

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击您要查看其内容的存储分区的名称。

  3. (可选)使用按名称前缀过滤字段,以将存储分区列表中列出的结果范围缩小为具有指定前缀的对象。

gsutil

使用带有 -r 标志的 gsutil ls 命令:

gsutil ls -r gs://[BUCKET_NAME]/**

其中:

  • [BUCKET_NAME] 是要列出其对象的存储分区的名称,例如 my-bucket

响应类似如下示例:

gs://[BUCKET_NAME]/[OBJECT_NAME1]
gs://[BUCKET_NAME]/[OBJECT_NAME2]
gs://[BUCKET_NAME]/[OBJECT_NAME3]
...

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

以下示例会列出存储分区中的所有对象:

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

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

以下示例会列出具有给定前缀的对象:

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

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

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

以下示例会列出存储分区中的所有对象:

private void ListObjects(string bucketName)
{
    var storage = StorageClient.Create();
    foreach (var storageObject in storage.ListObjects(bucketName, ""))
    {
        Console.WriteLine(storageObject.Name);
    }
}

以下示例会列出具有给定前缀的对象:

private void ListObjects(string bucketName, string prefix,
    string delimiter)
{
    var storage = StorageClient.Create();
    var options = new ListObjectsOptions() { Delimiter = delimiter };
    foreach (var storageObject in storage.ListObjects(
        bucketName, prefix, options))
    {
        Console.WriteLine(storageObject.Name);
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

以下示例会列出存储分区中的所有对象:

ctx := context.Background()

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 err
	}
	fmt.Fprintln(w, attrs.Name)
}

以下示例会列出具有给定前缀的对象:

// Prefixes and delimiters can be used to emulate directory listings.
// Prefixes can be used 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 := context.Background()

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 err
	}
	fmt.Fprintln(w, attrs.Name)
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

以下示例会列出存储分区中的所有对象:

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
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();
    Bucket bucket = storage.get(bucketName);
    Page<Blob> blobs = bucket.list();

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

以下示例会列出具有给定前缀的对象:

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
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();
    Bucket bucket = storage.get(bucketName);
    /**
     * 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 =
        bucket.list(
            Storage.BlobListOption.prefix(directoryPrefix),
            Storage.BlobListOption.currentDirectory());

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

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

以下示例会列出存储分区中的所有对象:

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

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

以下示例会列出具有给定前缀的对象:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const prefix = 'Prefix by which to filter, e.g. public/';
// const delimiter = 'Delimiter to use, e.g. /';

// 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

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

以下示例会列出存储分区中的所有对象:

use Google\Cloud\Storage\StorageClient;

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

以下示例会列出具有给定前缀的对象:

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects with specified prefix.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *
 * @return void
 */
function list_objects_with_prefix($bucketName, $prefix)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $options = ['prefix' => $prefix];
    foreach ($bucket->objects($options) as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

以下示例会列出存储分区中的所有对象:

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)

    for blob in blobs:
        print(blob.name)

以下示例会列出具有给定前缀的对象:

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

    Additionally, the same request will return blobs.prefixes populated with:

        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
    )

    print("Blobs:")
    for blob in blobs:
        print(blob.name)

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

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

以下示例会列出存储分区中的所有对象:

# bucket_name = "Your Google Cloud Storage 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

以下示例会列出具有给定前缀的对象:

# bucket_name = "Your Google Cloud Storage bucket name"
# prefix      = "Filter results to files whose names begin with this prefix"

require "google/cloud/storage"

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

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

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Bucket 请求调用 JSON API

    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/o"

    其中:

    • [ACCESS_TOKEN] 是您在第 1 步中生成的访问令牌。
    • [BUCKET_NAME] 是要列出其对象的存储分区的名称,例如 my-bucket

    您可以使用 prefix=[PREFIX] 查询字符串参数将结果限制为具有指定前缀的对象。

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Bucket 请求调用 XML API

    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]"

    其中:

    • [ACCESS_TOKEN] 是您在第 1 步中生成的访问令牌。
    • [BUCKET_NAME] 是要列出其对象的存储分区的名称,例如 my-bucket

    您可以使用 prefix=[PREFIX] 查询字符串参数将结果限制为具有指定前缀的存储分区。

后续步骤