List Objects

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

事前準備

如要取得列出物件所需的權限,請要求管理員為您授予值區的儲存空間物件檢視者 (roles/storage.objectViewer) 身分與存取權管理角色。如要列出代管資料夾中的物件,可以對包含要檢視物件的代管資料夾授予 roles/storage.objectViewer,而不必對值區授予。

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

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

所需權限

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

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

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

列出值區中的物件

控制台

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

    前往「Buckets」(值區) 頁面

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

指令列

使用 gcloud storage ls 指令:

gcloud storage ls gs://BUCKET_NAME

其中:

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

用戶端程式庫

C++

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

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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

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,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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


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,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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

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,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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

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,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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

/**
 * 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,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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

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,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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

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/


    Note: If you only want to list prefixes a/b/ and don't want to iterate over
    blobs, you can do

    ```
    for page in blobs.pages:
        print(page.prefixes)
    ```
    """

    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,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

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

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.s3nsapis.fr/storage/v1/b/BUCKET_NAME/o"

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

XML API

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

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

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

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

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

列出資料夾中的物件

控制台

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

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下包含資料夾的值區名稱。

  3. 在「Bucket details」(值區詳細資料) 頁面的「Objects」(物件) 分頁中,按一下要查看內容的資料夾名稱。

指令列

使用 gcloud storage ls 指令列出資料夾中的物件:

gcloud storage ls gs://BUCKET_NAME/FOLDER_NAME

其中:

  • BUCKET_NAME 是包含資料夾的值區名稱。例如:my-bucket

  • FOLDER_NAME 是包含要列出物件的資料夾名稱。例如:my-folder

REST API

JSON API

如要列出資料夾中的物件,請使用 list objects 要求,並搭配 prefixdelimiter 參數。設定 prefix 參數後,清單作業的範圍就會限定為只傳回前置字元下的物件和資料夾。設定 delimiter 參數後,回應中的 prefixes[] 清單會填入指定前置字元下的資料夾名稱。

例如:

  • 如要列出 bucket my-bucket 中資料夾 image/ 的所有物件,請使用下列網址: "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image&delimiter=/"

    這可能會傳回 my-bucket/image/cat.jpegmy-bucket/image/dog.jpeg 物件。

  • 如要在 image/ 中納入子資料夾內的物件,請移除 delimiter 參數:"https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image"

    這可能會傳回 my-bucket/image/cat.jpegmy-bucket/image/dog.jpegmy-bucket/image/dog/shiba.jpeg 物件。

如要在列出物件要求中使用萬用字元,並依 glob 運算式比對物件,請使用 matchGlob 參數。舉例來說,matchGlob=**.jpeg 會比對所有以 .jpeg 結尾的物件。使用 matchGlob 時,必須將 delimiter 設為 /

舉例來說,如要比對資料夾 image 中所有以 .jpeg 結尾的物件,請使用下列網址: "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image&delimiter=/&matchGlob=**.jpeg"

如要進一步瞭解如何使用參數篩選物件,請參閱「物件清單 JSON API 參考說明文件」。

用途

如果您只有列出資料夾中物件的權限,但沒有整個值區的權限,使用 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/

篩選物件

列出物件時,您可以在清單要求中使用前置字串或後置字串,依名稱篩選物件。

控制台

如要瞭解如何篩選及排序 bucket 或資料夾中的物件,請參閱篩選和排序

指令列

您可以在 gcloud storage ls 指令中使用萬用字元,依前置字串或後置字串篩選物件。舉例來說,以下指令只會列出值區 my-bucket 中名稱開頭為 image 且結尾為 .png 的物件:

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

如果要求成功,回應會類似以下內容:

gs://my-bucket/image.png
gs://my-bucket/image-dog.png
gs://my-bucket/image-cat.png
...

您可以使用雙星萬用字元,比對路徑中零個以上的資料夾層級。舉例來說,下列指令只會列出值區 my-bucket 中任何資料夾或子資料夾內,名稱結尾為 .jpeg 的物件:

gcloud storage ls gs://my-bucket/**/*.jpeg

如果要求成功,回應會類似以下內容:

gs://my-bucket/puppy.jpeg
gs://my-bucket/pug.jpeg
gs://my-bucket/pets/dog.jpeg
...

REST API

如要瞭解如何依資料夾或物件名稱前置字串篩選物件,請參閱列出資料夾中的物件

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

與平面命名空間值區相比,啟用階層式命名空間的值區底層結構會影響列出物件作業的效能。詳情請參閱「在啟用階層式命名空間的 bucket 中提升效能」。

後續步驟