使用前缀过滤条件列出存储桶中的对象

使用前缀列出 Cloud Storage 存储桶中的对象。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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 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"
)

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

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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器