建立及管理資料夾

本頁面說明如何在啟用階層命名空間的情況下,建立、列出、上傳、刪除及取得值區中資料夾的中繼資料。

事前準備

請確認已為值區啟用階層命名空間。如要進一步瞭解如何在值區中啟用階層式命名空間,請參閱「建立已啟用階層式命名空間的值區」。

建立資料夾

本節說明如何建立資料夾。

控制台

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

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下要建立資料夾的值區名稱。
  3. 在「Bucket details」頁面中,按一下「Create folder」建立空白資料夾。
  4. 在「名稱」欄位中,輸入資料夾的名稱。如要瞭解命名注意事項,請參閱「注意事項」。
  5. 按一下「建立」。

    新建立的資料夾會顯示在「Folder browser」窗格中。

指令列

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 在開發環境中執行 gcloud storage folders create 指令:

    gcloud storage folders create --recursive gs://BUCKET_NAME/FOLDER_NAME

    其中:

    • BUCKET_NAME 是值區的名稱。例如 my-bucket
    • FOLDER_NAME 是您要建立的資料夾名稱。例如,my-folder/。如要瞭解資料夾名稱,請參閱資料夾總覽說明文件
    • --recursive 是標記,可自動建立資料夾中所有不存在的上層資料夾。如果已存在上層資料夾,則可選擇使用這項設定。

    如果要求成功,指令會傳回以下訊息:

    Completed 1/1

用戶端程式庫

C++

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

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
  auto folder = client.CreateFolder(
      parent, google::storage::control::v2::Folder{}, folder_id);
  if (!folder) throw std::move(folder).status();

  std::cout << "Created folder: " << folder->name() << "\n";
}

C#

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

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

using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlCreateFolderSample
{
    public Folder StorageControlCreateFolder(string bucketName = "your-unique-bucket-name",
        string folderName = "your_folder_name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        var request = new CreateFolderRequest
        {
            // Set project to "_" to signify globally scoped bucket
            Parent = BucketName.FormatProjectBucket("_", bucketName),
            FolderId = folderName
        };

        Folder folder = storageControl.CreateFolder(request);

        Console.WriteLine($"Folder {folderName} created in bucket {bucketName}");
        return folder;
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
)

// createFolder creates a folder in the bucket with the given name.
func createFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	req := &controlpb.CreateFolderRequest{
		Parent:   fmt.Sprintf("projects/_/buckets/%v", bucket),
		FolderId: folder,
	}
	f, err := client.CreateFolder(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateFolder(%q): %w", folder, err)
	}

	fmt.Fprintf(w, "created folder with path %q", f.Name)
	return nil
}

Java

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

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

import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.CreateFolderRequest;
import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class CreateFolder {

  public static void createFolder(String bucketName, String folderName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the folder within the bucket
    // String folderName = "your-unique-folder-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      CreateFolderRequest request =
          CreateFolderRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setParent(BucketName.format("_", bucketName))
              .setFolderId(folderName)
              .build();

      Folder newFolder = storageControl.createFolder(request);

      System.out.printf("Created folder: %s%n", newFolder.getName());
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// The name of the folder to be created
// const folderName = 'folderName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callCreateFolder() {
  const bucketPath = controlClient.bucketPath('_', bucketName);

  // Create the request
  const request = {
    parent: bucketPath,
    folderId: folderName,
  };

  // Run request
  const [response] = await controlClient.createFolder(request);
  console.log(`Created folder: ${response.name}.`);
}

callCreateFolder();

PHP

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

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

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\CreateFolderRequest;

/**
 * Create a new folder in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $folderName The name of your folder inside the bucket.
 *        (e.g. 'my-folder')
 */
function create_folder(string $bucketName, string $folderName): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->bucketName('_', $bucketName);

    $request = new CreateFolderRequest([
        'parent' => $formattedName,
        'folder_id' => $folderName,
    ]);

    $folder = $storageControlClient->createFolder($request);

    printf('Created folder: %s', $folder->getName());
}

Python

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

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

from google.cloud import storage_control_v2


def create_folder(bucket_name: str, folder_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    # The name of the folder to be created
    # folder_name = "folder-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    project_path = storage_control_client.common_project_path("_")
    bucket_path = f"{project_path}/buckets/{bucket_name}"

    request = storage_control_v2.CreateFolderRequest(
        parent=bucket_path,
        folder_id=folder_name,
    )
    response = storage_control_client.create_folder(request=request)

    print(f"Created folder: {response.name}")

Ruby

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

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

def create_folder bucket_name:, folder_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of the folder to be created
  # folder_name = "folder-name"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage bucket path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  bucket_path = storage_control.bucket_path project: "_", bucket: bucket_name

  request = Google::Cloud::Storage::Control::V2::CreateFolderRequest.new parent: bucket_path, folder_id: folder_name

  response = storage_control.create_folder request

  puts "Created folder: #{response.name}"
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 建立 JSON 檔案,其中包含資料夾的設定,且必須包含資料夾的 name。如需完整的設定清單,請參閱 資料夾:插入說明文件。以下是必要設定:
    {
      "name": "FOLDER_NAME",
    }

    其中 FOLDER_NAME 是您要建立的資料夾名稱。例如:my-folder/。如需瞭解資料夾名稱的相關資訊,請參閱資料夾總覽說明文件

  3. 使用 cURL 呼叫 JSON API
    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders?recursive=true"

    其中:

    • JSON_FILE_NAME 是 JSON 檔案的名稱,其中包含資料夾的設定。
    • BUCKET_NAME 是您要建立資料夾的值區名稱。
    • recursive 設為 true,系統會自動建立所有不存在的上層資料夾,以及資料夾本身。如果已存在上層資料夾,則可選擇使用這項設定。

列出資料夾

本節說明如何列出資料夾。

控制台

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

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下要列出資料夾的值區名稱。

  3. 在「資料夾瀏覽器」窗格中,使用展開箭頭 展開值區內的資料夾清單。

    清單會顯示 bucket 中的資料夾、模擬資料夾和受管理的資料夾。

指令列

如要列出資料夾中所有資料夾,請執行 gcloud storage folders list 指令:

gcloud storage folders list gs://BUCKET_NAME/

其中:

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

成功的回應如下所示:

bucket: hns-bucket
id: hns-bucket/A/
kind: storage#folder
name: A/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/A
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/B/
kind: storage#folder
name: B/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/B
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/B/D/
kind: storage#folder
name: D/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/B/D
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/C/
kind: storage#folder
name: C/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/C
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/C/E/
kind: storage#folder
name: E/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/C/E
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
...

用戶端程式庫

C++

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

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name) {
  auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
  for (auto folder : client.ListFolders(parent)) {
    if (!folder) throw std::move(folder).status();
    std::cout << folder->name() << "\n";
  }

  std::cout << bucket_name << std::endl;
}

C#

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

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

using Google.Cloud.Storage.Control.V2;
using System;
using System.Collections.Generic;

public class StorageControlListFoldersSample
{
    public IEnumerable<Folder> StorageControlListFolders(string bucketName = "your-unique-bucket-name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        // Use "_" for project ID to signify globally scoped bucket
        string bucketResourceName = BucketName.FormatProjectBucket("_", bucketName);
        var folders = storageControl.ListFolders(bucketResourceName);

        foreach (var folder in folders)
        {
            Console.Write(folder.Name);
        }
        return folders;
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
	"google.golang.org/api/iterator"
)

// listFolders lists all folders present in the bucket.
func listFolders(w io.Writer, bucket string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// Construct bucket path for a bucket containing folders.
	bucketPath := fmt.Sprintf("projects/_/buckets/%v", bucket)

	// List all folders present.
	req := &controlpb.ListFoldersRequest{
		Parent: bucketPath,
	}
	it := client.ListFolders(ctx, req)
	for {
		f, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListFolders(%q): %w", bucketPath, err)
		}
		fmt.Fprintf(w, "got folder %v\n", f.Name)
	}

	return nil
}

Java

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

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


import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.ListFoldersRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class ListFolders {

  public static void listFolders(String bucketName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      ListFoldersRequest request =
          ListFoldersRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setParent(BucketName.format("_", bucketName))
              .build();

      Iterable<Folder> folders = storageControl.listFolders(request).iterateAll();
      for (Folder folder : folders) {
        System.out.printf("Found folder: %s%n", folder.getName());
      }
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callListFolders() {
  const bucketPath = controlClient.bucketPath('_', bucketName);

  // Create the request
  const request = {
    parent: bucketPath,
  };

  // Run request
  const [folders] = await controlClient.listFolders(request);
  for (const curFolder of folders) {
    console.log(curFolder.name);
  }
}

callListFolders();

PHP

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

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

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\ListFoldersRequest;

/**
 * List folders in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_folders(string $bucketName): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->bucketName('_', $bucketName);

    $request = new ListFoldersRequest([
        'parent' => $formattedName,
    ]);

    $folders = $storageControlClient->listFolders($request);

    foreach ($folders as $folder) {
        printf('Folder name: %s' . PHP_EOL, $folder->getName());
    }
}

Python

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

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

from google.cloud import storage_control_v2


def list_folders(bucket_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    project_path = storage_control_client.common_project_path("_")
    bucket_path = f"{project_path}/buckets/{bucket_name}"

    request = storage_control_v2.ListFoldersRequest(
        parent=bucket_path,
    )

    page_result = storage_control_client.list_folders(request=request)
    for folder in page_result:
        print(folder)

    print(f"Listed folders in bucket {bucket_name}")

Ruby

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

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

def list_folders bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage bucket path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  bucket_path = storage_control.bucket_path project: "_", bucket: bucket_name

  request = Google::Cloud::Storage::Control::V2::ListFoldersRequest.new parent: bucket_path

  response = storage_control.list_folders request

  puts response.response.folders
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/folders"

    其中 BUCKET_NAME 是包含要列出的資料夾的值區名稱。例如:my-bucket

上傳資料夾

本節說明如何將資料夾上傳至值區。

控制台

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

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,點選要上傳資料夾的值區名稱。

  3. 在「Bucket details」分頁中,執行下列任一操作:

    • 將資料夾從桌面或檔案管理員拖曳到 Google Cloud 主控台的主要窗格。

    • 依序點選「上傳」>「上傳資料夾」,在出現的對話方塊中選取要上傳的資料夾,然後按一下「開啟」

如要瞭解如何在 Google Cloud 控制台中取得 Cloud Storage 作業失敗的詳細錯誤資訊,請參閱疑難排解

指令列

使用加上 --recursive 旗標的 gcloud storage cp 指令:

gcloud storage cp --recursive FOLDER_LOCATION gs://DESTINATION_BUCKET_NAME

其中:

  • FOLDER_LOCATION 是您要上傳的資料夾本機路徑。例如:../uploads/my-folder/

  • DESTINATION_BUCKET_NAME 是您要上傳資料夾的值區名稱。例如:my-bucket

如果成功,回應會類似以下範例:

Copying file://DIR/OBJ1 at 10.06.32 PM.png to gs://BUCKET_NAME/DIR/OBJ1 at 10.06.32 PM.png
Copying file://DIR/OBJ1 at 10.06.32 PM.png to gs://BUCKET_NAME/DIR/OBJ1 at 10.06.32 PM.png
Completed files 2/2 | 1.7MiB/1.7MiB

刪除資料夾

本節說明如何刪除資料夾。

控制台

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

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下要刪除資料夾的值區名稱。

  3. 在「資料夾瀏覽器」窗格中,使用展開箭頭 展開值區內的資料夾清單。

  4. 找出要刪除的資料夾。

  5. 按一下資料夾的 「更多操作」選單。

  6. 按一下「刪除資料夾」

  7. 如要確認要刪除資料夾,請在「Delete」欄位中輸入 DELETE

  8. 點選「刪除」。

    系統會從 Cloud Storage 值區中刪除資料夾及其內容,包括已儲存的物件和其他受管理的資料夾。

指令列

如要刪除空資料夾,請執行 gcloud storage folders delete 指令:

gcloud storage folders delete gs://BUCKET_NAME/FOLDER_NAME

其中:

  • BUCKET_NAME 是值區名稱。例如:my-bucket

  • FOLDER_NAME 是您要刪除的資料夾名稱。例如:my-folder/

用戶端程式庫

C++

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

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const name = std::string{"projects/_/buckets/"} + bucket_name +
                    "/folders/" + folder_id;
  auto status = client.DeleteFolder(name);
  if (!status.ok()) throw std::move(status);

  std::cout << "Deleted folder: " << folder_id << "\n";
}

C#

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

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

using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlDeleteFolderSample
{
    public void StorageControlDeleteFolder(string bucketName = "your-unique-bucket-name",
        string folderName = "your_folder_name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        string folderResourceName =
            // Set project to "_" to signify globally scoped bucket
            FolderName.FormatProjectBucketFolder("_", bucketName, folderName);

        storageControl.DeleteFolder(folderResourceName);

        Console.WriteLine($"Deleted folder {folderName} from bucket {bucketName}");
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
)

// deleteFolder deletes the folder with the given name.
func deleteFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// Construct folder path including the bucket name.
	folderPath := fmt.Sprintf("projects/_/buckets/%v/folders/%v", bucket, folder)

	req := &controlpb.DeleteFolderRequest{
		Name: folderPath,
	}
	if err := client.DeleteFolder(ctx, req); err != nil {
		return fmt.Errorf("DeleteFolder(%q): %w", folderPath, err)
	}

	fmt.Fprintf(w, "deleted folder %q", folderPath)
	return nil
}

Java

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

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


import com.google.storage.control.v2.DeleteFolderRequest;
import com.google.storage.control.v2.FolderName;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class DeleteFolder {

  public static void deleteFolder(String bucketName, String folderName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the folder within the bucket
    // String folderName = "your-unique-folder-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      // Set project to "_" to signify globally scoped bucket
      String folderResourceName = FolderName.format("_", bucketName, folderName);
      DeleteFolderRequest request =
          DeleteFolderRequest.newBuilder().setName(folderResourceName).build();

      storageControl.deleteFolder(request);

      System.out.printf("Deleted folder: %s%n", folderResourceName);
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// The name of the folder to be deleted
// const folderName = 'folderName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callDeleteFolder() {
  const folderPath = controlClient.folderPath('_', bucketName, folderName);

  // Create the request
  const request = {
    name: folderPath,
  };

  // Run request
  await controlClient.deleteFolder(request);
  console.log(`Deleted folder: ${folderName}.`);
}

callDeleteFolder();

PHP

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

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

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\DeleteFolderRequest;

/**
 * Delete a folder in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $folderName The name of your folder inside the bucket.
 *        (e.g. 'my-folder')
 */
function delete_folder(string $bucketName, string $folderName): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->folderName('_', $bucketName, $folderName);

    $request = new DeleteFolderRequest([
        'name' => $formattedName,
    ]);

    $storageControlClient->deleteFolder($request);

    printf('Deleted folder: %s', $folderName);
}

Python

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

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

from google.cloud import storage_control_v2


def delete_folder(bucket_name: str, folder_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    # The name of the folder to be deleted
    # folder_name = "folder-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    folder_path = storage_control_client.folder_path(
        project="_", bucket=bucket_name, folder=folder_name
    )

    request = storage_control_v2.DeleteFolderRequest(
        name=folder_path,
    )
    storage_control_client.delete_folder(request=request)

    print(f"Deleted folder {folder_name}")

Ruby

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

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

def delete_folder bucket_name:, folder_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"
  #
  # Name of the folder you want to delete
  # folder_name = "name-of-the-folder"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage folder path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  folder_path = storage_control.folder_path project: "_", bucket: bucket_name, folder: folder_name

  request = Google::Cloud::Storage::Control::V2::DeleteFolderRequest.new name: folder_path

  storage_control.delete_folder request

  puts "Deleted folder: #{folder_name}"
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 DELETE 資料夾要求呼叫 JSON API

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

    其中:

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

    • FOLDER_NAME 是您要刪除的資料夾的 URL 編碼名稱。例如 my-folder/,網址編碼為 my-folder%2F

取得資料夾的中繼資料

本節說明如何取得資料夾的中繼資料

指令列

如要取得資料夾的中繼資料,請執行 gcloud storage folders describe 指令:

gcloud storage folders describe gs://BUCKET_NAME/FOLDER_NAME

其中:

  • BUCKET_NAME 是值區名稱,其中包含您要擷取其中繼資料的資料夾。例如:my-bucket
  • FOLDER_NAME 是您要擷取其中繼資料的資料夾名稱。例如:my-folder/

用戶端程式庫

C++

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

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const name = std::string{"projects/_/buckets/"} + bucket_name +
                    "/folders/" + folder_id;
  auto folder = client.GetFolder(name);
  if (!folder) throw std::move(folder).status();

  std::cout << "Got folder: " << folder->name() << "\n";
}

C#

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

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

using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlGetFolderSample
{
    public Folder StorageControlGetFolder(string bucketName = "your-unique-bucket-name",
        string folderName = "your_folder_name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        string folderResourceName =
            // Set project to "_" to signify globally scoped bucket
            FolderName.FormatProjectBucketFolder("_", bucketName, folderName);

        Folder folder = storageControl.GetFolder(folderResourceName);

        Console.WriteLine($"Got folder: {folder.Name}");
        return folder;
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
)

// getFolder gets metadata for the folder with the given name.
func getFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// Construct folder path including the bucket name.
	folderPath := fmt.Sprintf("projects/_/buckets/%v/folders/%v", bucket, folder)

	req := &controlpb.GetFolderRequest{
		Name: folderPath,
	}
	f, err := client.GetFolder(ctx, req)
	if err != nil {
		return fmt.Errorf("GetFolder(%q): %w", folderPath, err)
	}

	fmt.Fprintf(w, "got folder metadata: %+v", f)
	return nil
}

Java

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

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


import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.FolderName;
import com.google.storage.control.v2.GetFolderRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class GetFolder {

  public static void getFolder(String bucketName, String folderName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the folder within the bucket
    // String folderName = "your-unique-folder-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      GetFolderRequest request =
          GetFolderRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setName(FolderName.format("_", bucketName, folderName))
              .build();

      Folder newFolder = storageControl.getFolder(request);

      System.out.printf("Got folder: %s%n", newFolder.getName());
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// The name of the folder to get
// const folderName = 'folderName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callGetFolder() {
  const folderPath = controlClient.folderPath('_', bucketName, folderName);

  // Create the request
  const request = {
    name: folderPath,
  };

  // Run request
  const [response] = await controlClient.getFolder(request);
  console.log(`Got folder: ${response.name}.`);
}

callGetFolder();

PHP

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

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

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\GetFolderRequest;

/**
 * Get a folder in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $folderName The name of your folder inside the bucket.
 *        (e.g. 'my-folder')
 */
function get_folder(string $bucketName, string $folderName): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->folderName('_', $bucketName, $folderName);

    $request = new GetFolderRequest([
        'name' => $formattedName,
    ]);

    $folder = $storageControlClient->getFolder($request);

    printf($folder->getName());
}

Python

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

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

from google.cloud import storage_control_v2


def get_folder(bucket_name: str, folder_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    # The name of the folder
    # folder_name = "folder-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    folder_path = storage_control_client.folder_path(
        project="_", bucket=bucket_name, folder=folder_name
    )

    request = storage_control_v2.GetFolderRequest(
        name=folder_path,
    )
    response = storage_control_client.get_folder(request=request)

    print(f"Got folder: {response.name}")

Ruby

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

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

def get_folder bucket_name:, folder_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of the folder to be created
  # folder_name = "folder-name"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage folder path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  folder_path = storage_control.folder_path project: "_", bucket: bucket_name, folder: folder_name

  request = Google::Cloud::Storage::Control::V2::GetFolderRequest.new name: folder_path

  response = storage_control.get_folder request

  puts "Got folder #{response.name}"
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 GET 資料夾要求呼叫 JSON API

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

    其中:

    • BUCKET_NAME 是值區名稱,其中包含您要擷取其中繼資料的資料夾。例如:my-bucket

    • FOLDER_NAME 是您要擷取中繼資料的資料夾名稱,以網址編碼表示。例如 my-folder/,網址編碼為 my-folder%2F

管理資料夾存取權

本節將說明如何設定 Identity and Access Management (IAM) 政策,藉此管理資料夾的存取權,以便精細控管值區中特定物件群組的存取權。

如要管理資料夾的存取權,請按照下列步驟操作:

  1. 建立與現有資料夾名稱相同的受管理資料夾,即可啟用資料夾管理功能。如需詳細操作說明,請參閱「建立受控資料夾」。

  2. 在您建立的受管理資料夾上設定及管理身分與存取權管理 (IAM) 政策

後續步驟

歡迎試用

如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用 Cloud Storage 的成效。新客戶可以獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。

免費試用 Cloud Storage