列出对象

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

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

Console

  1. 在 Google Cloud Platform 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 参考文档

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

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
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 参考文档

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

Page<Blob> blobs = bucket.list();
for (Blob blob : blobs.iterateAll()) {
  // do something with the blob
}

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

Page<Blob> blobs =
    storage.list(
        bucketName, BlobListOption.currentDirectory(), BlobListOption.prefix(directory));
for (Blob blob : blobs.iterateAll()) {
  // do something with the blob
}

Node.js

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

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

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

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

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

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

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

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

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

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

/**
 * 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. /';

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

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 参考文档

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

def list_blobs(bucket_name):
    """Lists all the blobs in the bucket."""
    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)

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

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

    """
    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 参考文档

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"

require "google/cloud/storage"

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

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

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

# project_id  = "Your Google Cloud project ID"
# 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 project_id: project_id
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://www.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] 查询字符串参数将结果限制为具有指定前缀的存储分区。

后续步骤

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Storage
需要帮助?请访问我们的支持页面