Mencantumkan objek

Halaman ini menunjukkan cara menampilkan daftar objek yang tersimpan di bucket Cloud Storage, yang diurutkan dalam listing secara leksikografis menurut nama.

Sebelum memulai

Untuk mendapatkan izin yang diperlukan untuk mencantumkan objek, minta administrator untuk memberi Anda peran IAM Storage Object Viewer (roles/storage.objectViewer) untuk bucket yang berisi objek yang ingin Anda cantumkan. Jika ingin mencantumkan objek dalam folder terkelola, Anda dapat memberikan roles/storage.objectViewer pada folder terkelola yang berisi objek yang ingin Anda lihat, bukan bucket.

Jika Anda berencana menggunakan konsol Trusted Cloud untuk melakukan tugas di halaman ini, minta administrator Anda untuk memberi Anda peran dasar Viewer (roles/viewer) selain peran Storage Object Viewer (roles/storage.objectViewer).

Peran ini berisi izin yang diperlukan untuk mencantumkan objek. Untuk melihat izin yang benar-benar diperlukan, luaskan bagian Izin yang diperlukan:

Izin yang diperlukan

  • storage.objects.list
  • storage.buckets.list
    • Izin ini hanya diperlukan jika Anda ingin menggunakan konsol Trusted Cloud untuk melakukan tugas di halaman ini.

Anda juga bisa mendapatkan izin ini dengan peran standar atau peran khusus lainnya.

Untuk informasi tentang cara memberikan peran untuk bucket, lihat Menggunakan IAM dengan bucket.

Membuat daftar objek dalam bucket

Konsol

  1. Di Trusted Cloud konsol, buka halaman Bucket Cloud Storage.

    Buka Buckets

  2. Di daftar bucket, klik nama bucket yang isinya ingin Anda lihat.

Command line

Gunakan perintah gcloud storage ls:

gcloud storage ls gs://BUCKET_NAME

Dengan:

  • BUCKET_NAME adalah nama bucket yang berisi objek yang ingin Anda cantumkan. Contoh, my-bucket.

Library klien

C++

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:

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

Contoh berikut mencantumkan objek dengan awalan tertentu:

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#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:


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

Contoh berikut mencantumkan objek dengan awalan tertentu:


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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:

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
}

Contoh berikut mencantumkan objek dengan awalan tertentu:

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:

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

Contoh berikut mencantumkan objek dengan awalan tertentu:

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:

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

Contoh berikut mencantumkan objek dengan awalan tertentu:

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:

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

Contoh berikut mencantumkan objek dengan awalan tertentu:

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:

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)

Contoh berikut mencantumkan objek dengan awalan tertentu:

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

Contoh berikut mencantumkan semua objek dalam bucket:

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

Contoh berikut mencantumkan objek dengan awalan tertentu:

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. Menginstal dan melakukan inisialisasi gcloud CLI, yang memungkinkan Anda membuat token akses untuk header Authorization.

  2. Gunakan cURL untuk memanggil JSON API dengan permintaan untuk mencantumkan objek:

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

    Dengan BUCKET_NAME adalah nama bucket yang objeknya ingin Anda cantumkan. Contoh, my-bucket.

XML API

  1. Menginstal dan melakukan inisialisasi gcloud CLI, yang memungkinkan Anda membuat token akses untuk header Authorization.

  2. Gunakan cURLuntuk memanggil XML API dengan permintaan GET Bucket:

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

    Dengan BUCKET_NAME adalah nama bucket yang objeknya ingin Anda cantumkan. Contoh, my-bucket.

    Anda dapat menggunakan parameter string kueri prefix=PREFIX untuk membatasi hasil pada objek yang memiliki awalan yang ditentukan.

Mencantumkan objek dalam folder

Konsol

  1. Di Trusted Cloud konsol, buka halaman Bucket Cloud Storage.

    Buka Buckets

  2. Di daftar bucket, klik nama bucket yang berisi folder.

  3. Di tab Objects pada halaman Bucket details, klik nama folder yang isinya ingin Anda lihat.

Command line

Gunakan perintah gcloud storage ls untuk mencantumkan objek dalam folder:

gcloud storage ls gs://BUCKET_NAME/FOLDER_NAME

Dengan:

  • BUCKET_NAME adalah nama bucket yang berisi folder. Contoh, my-bucket.

  • FOLDER_NAME adalah nama folder yang berisi objek yang ingin Anda cantumkan. Contoh, my-folder.

REST API

JSON API

Untuk mencantumkan objek dalam folder, gunakan permintaan daftar objek dengan parameter prefix dan delimiter. Jika parameter prefix ditetapkan, operasi daftar akan dicakup untuk hanya menampilkan objek dan folder di bawah awalan. Jika parameter delimiter disetel, daftar prefixes[] dalam respons akan diisi dengan nama folder di bawah awalan yang ditentukan.

Contoh:

  • Untuk mencantumkan semua objek di folder image/ dalam bucket my-bucket, gunakan URL berikut: "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image&delimiter=/".

    Hal ini dapat menampilkan objek my-bucket/image/cat.jpeg dan my-bucket/image/dog.jpeg.

  • Untuk menyertakan objek dalam subfolder di image/, hapus parameter delimiter: "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image".

    Hal ini dapat menampilkan objek my-bucket/image/cat.jpeg, my-bucket/image/dog.jpeg, dan my-bucket/image/dog/shiba.jpeg.

Untuk menggunakan karakter pengganti dalam permintaan daftar objek dan mencocokkan objek berdasarkan ekspresi glob, gunakan parameter matchGlob. Misalnya, matchGlob=**.jpeg cocok dengan semua objek yang diakhiri dengan .jpeg. Saat menggunakan matchGlob, Anda harus menetapkan delimiter ke /.

Misalnya, gunakan URL berikut untuk mencocokkan semua objek dalam folder image yang diakhiri dengan .jpeg: "https://storage.s3nsapis.fr/storage/v1/b/my-bucket/o?prefix=image&delimiter=/&matchGlob=**.jpeg"

Untuk mengetahui detail selengkapnya tentang penggunaan parameter untuk memfilter objek, lihat Dokumentasi referensi JSON API daftar objek.

Kasus penggunaan

Menggunakan prefix untuk mencantumkan konten folder dapat berguna jika Anda hanya memiliki izin untuk mencantumkan objek dalam folder, tetapi tidak seluruh bucket. Misalnya, Anda memiliki peran IAM Storage Object Viewer (roles/storage.objectViewer) untuk folder terkelola my-bucket/my-managed-folder-a/, tetapi tidak untuk folder terkelola my-bucket/my-managed-folder-b/. Untuk menampilkan hanya objek dalam my-managed-folder-a, Anda dapat menentukan prefix=my-managed-folder-a/.

Memfilter objek

Saat mencantumkan objek, Anda dapat menggunakan awalan atau akhiran dalam permintaan daftar untuk memfilter objek menurut nama.

Konsol

Lihat memfilter dan mengurutkan untuk mengetahui informasi tentang cara memfilter dan mengurutkan objek dalam bucket atau folder.

Command line

Anda dapat menggunakan karakter pengganti dalam perintah gcloud storage ls untuk memfilter objek menurut awalan atau akhiran. Misalnya, perintah berikut hanya mencantumkan objek di bucket my-bucket yang namanya diawali dengan image dan diakhiri dengan .png:

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

Jika permintaan berhasil, responsnya akan terlihat mirip dengan berikut ini:

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

Anda dapat menggunakan karakter pengganti bintang ganda untuk mencocokkan nol atau beberapa tingkat folder dalam jalur. Misalnya, perintah berikut hanya mencantumkan objek yang namanya berakhir dengan .jpeg di folder atau subfolder mana pun dalam bucket my-bucket:

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

Jika permintaan berhasil, responsnya akan terlihat mirip dengan berikut ini:

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

REST API

Lihat mencantumkan objek dalam folder untuk mengetahui informasi tentang cara memfilter objek menurut awalan nama folder atau objek.

Pertimbangan performa saat mencantumkan objek

Struktur dasar bucket dengan namespace hierarkis yang diaktifkan memengaruhi performa operasi pencantuman objek, jika dibandingkan dengan bucket namespace datar. Untuk mengetahui informasi selengkapnya, lihat Mengoptimalkan performa di bucket dengan namespace hierarkis yang diaktifkan.

Langkah berikutnya