List Objects

這個頁面說明如何列出 Cloud Storage 值區中的物件,物件會按照名稱的字母順序排序。

事前準備

如要取得列出物件所需的權限,請要求管理員為您授予值區的儲存空間物件檢視者 (roles/storage.objectViewer) 身分與存取權管理角色,該值區包含您要列出的物件。

如果您打算使用 Google Cloud 控制台執行本頁面的工作,請要求管理員除了 Storage 物件檢視者 (roles/storage.objectViewer) 角色外,也授予您檢視者 (roles/viewer) 基本角色。

這些角色具備列出物件所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.objects.list
  • storage.buckets.list
    • 如要使用 Google Cloud 控制台執行這個頁面的工作,才需要這項權限。

您也可以透過其他預先定義的角色自訂角色取得這些權限。

如需授予值區角色的相關資訊,請參閱「搭配值區使用 IAM」。

列出值區中的物件

如要列出值區中的物件,請完成下列步驟:

控制台

  1. 在 Google Cloud 控制台,前往「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下要查看內容的值區名稱。

  3. 選用:使用篩選和排序功能,限制並整理清單中的結果。

指令列

使用 gcloud storage ls 指令並加上 --recursive 旗標:

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

其中:

  • BUCKET_NAME 是您要列出物件的值區名稱。例如:my-bucket

回應類似下列範例:

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

用戶端程式庫

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:

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

下列範例會列出具有指定前置字串的物件:

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#

詳情請參閱 Cloud Storage C# API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:


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

下列範例會列出具有指定前置字串的物件:


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

詳情請參閱 Cloud Storage Go API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:

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
}

下列範例會列出具有指定前置字串的物件:

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

詳情請參閱 Cloud Storage Java API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:

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

下列範例會列出具有指定前置字串的物件:

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

詳情請參閱 Cloud Storage Node.js API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:

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

下列範例會列出具有指定前置字串的物件:

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

詳情請參閱 Cloud Storage PHP API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:

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

下列範例會列出具有指定前置字串的物件:

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

詳情請參閱 Cloud Storage Python API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:

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)

下列範例會列出具有指定前置字串的物件:

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

詳情請參閱 Cloud Storage Ruby API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會列出值區中所有的物件:

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

下列範例會列出具有指定前置字串的物件:

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

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過列出物件的要求呼叫 JSON API

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"

    其中 BUCKET_NAME 是要列出物件的值區名稱。例如:my-bucket

    您可以使用 includeFoldersAsPrefixes=True 查詢參數,在清單結果中傳回受管理資料夾。使用 includeFoldersAsPrefixes 參數時,delimiter 參數必須設為 /

XML API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 使用 cURL透過 GET 值區要求呼叫 XML API

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?list-type=2"

    其中 BUCKET_NAME 是要列出物件的值區名稱。例如:my-bucket

    您可以使用 prefix=PREFIX 查詢字串參數,將結果限制為具有指定前置字元的物件。

篩選物件

控制台

如要使用 Google Cloud 控制台依名稱前置字串篩選物件,請使用「Bucket details」(值區詳細資料) 頁面中的「Filter objects and folders」(篩選物件和資料夾) 欄位。

如要瞭解如何使用 Google Cloud 控制台進行其他篩選,請參閱篩選和排序

指令列

使用 Google Cloud CLI 列出物件時,您可以運用萬用字元,篩選出開頭或結尾為特定前置字元/後置字元的物件。舉例來說,下列指令會比對開頭為 image 且結尾為 .png 的物件:

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

如要進一步瞭解如何使用 Google Cloud CLI 進行篩選,請參閱gcloud storage ls 說明文件

REST API

JSON API

使用 Cloud Storage JSON API 列出物件時,可以透過 prefixmatchGlob 查詢字串參數篩選結果。如要瞭解如何使用這些查詢字串參數,請參閱物件清單 JSON API 參考說明文件

依前置字串篩選

您可以使用 prefix=PREFIX 或查詢字串參數,將結果限制為具有指定前置字元的物件或受管理資料夾。舉例來說,如要列出前置字串為 folder/subfolder/ 的值區 my-bucket 中所有物件,請使用網址 "https://storage.googleapis.com/storage/v1/b/my-bucket/o?prefix=folder/subfolder/" 提出物件列出要求。

如果您只有權限列出代管資料夾中的物件,但沒有整個值區的權限,使用 prefix 列出代管資料夾的內容就很有用。舉例來說,假設您擁有受管理資料夾 my-bucket/my-managed-folder-a/ 的 Storage 物件檢視者 (roles/storage.objectViewer) IAM 角色,但沒有受管理資料夾 my-bucket/my-managed-folder-b/ 的角色。如要只傳回 my-managed-folder-a 中的物件,可以指定 prefix=my-managed-folder-a/

如要將結果限制在代管資料夾和其中的物件,請務必在 PREFIX 後方加上 / (例如 prefix=my-managed-folder/)。否則結果也可能包含代管資料夾附近的物件。在本範例中,您有一個包含下列物件的 bucket:

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

指定 prefix=abc/ 可傳回物件 my-bucket/abc/object.txt,指定 prefix=abc 則可傳回 my-bucket/abc.txtmy-bucket/abc/object.txt

依 glob 運算式篩選

您可以使用 matchGlob=GLOB_PATTERN 查詢字串參數,將結果篩選為只顯示符合特定 glob 運算式的物件。舉例來說,matchGlob=**.jpeg 可用於比對結尾為 .jpeg 的所有物件。

如果要求使用 matchGlob 參數,且包含設為 / 以外值的 delimiter 參數,就會失敗。

列出物件時的效能注意事項

與扁平命名空間值區相比,啟用階層命名空間的值區基礎結構可能會影響列出物件作業的效能。如要進一步瞭解如何最佳化效能,以便列出已啟用階層式命名空間的 bucket 中的物件,請參閱「列出物件」。

後續步驟