列出对象

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

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

Console

  1. 在 Google Cloud Platform Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,选择要查看其内容的存储分区。

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

    “按前缀过滤”文本框。

gsutil

使用带有 -r 标志的 gsutil ls 命令,并将 [VALUES_IN_BRACKETS] 替换为适当的值:

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

响应类似如下示例:

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

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()
    bucket = storage_client.get_bucket(bucket_name)

    blobs = bucket.list_blobs()

    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()
    bucket = storage_client.get_bucket(bucket_name)

    blobs = bucket.list_blobs(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 调用 JSON API,并将 [VALUES_IN_BRACKETS] 替换为适当的值:
    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o"

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

有关详情,请参阅对象:列出 JSON 参考页面。

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL 调用 XML API,并将 [VALUES_IN_BRACKETS] 替换为适当的值:
    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://storage.googleapis.com/[BUCKET_NAME]"

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

有关详情,请参阅列出对象 XML 参考页面。

后续步骤

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

发送以下问题的反馈:

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