列出物件

這個頁面說明如何列出 Cloud Storage 值區中儲存的物件,物件會按照名稱的字母順序排序。如需物件總覽,請參閱重要詞彙

如要列出值區中的物件:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,選取要查看內容的值區。

  3. 或者,您也可以使用「Filter by prefix...」(依前置字串篩選…) 欄位指定前置字串,以縮小值區清單中列出的物件結果。

    依前置字串篩選文字方塊

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
需要協助嗎?請前往我們的支援網頁