创建和管理托管文件夹

本指南介绍如何创建、列出和删除托管文件夹

准备工作

如需创建和管理托管式文件夹,您必须先启用统一存储桶级访问权限并获取所需的 IAM 角色。

启用统一存储桶级访问权限

启用统一存储桶级访问权限(如果您尚未启用)。

获取所需角色

如需获取创建和管理托管式文件夹所需的权限,请让管理员向您授予存储桶的 Storage Folder Admin (roles/storage.folderAdmin) IAM 角色。

此预定义角色可提供创建和管理托管式文件夹所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

如需创建和管理托管式文件夹,需要具备以下权限:

  • 如需创建托管式文件夹,请执行以下操作: storage.managedFolders.create
  • 如需通过列出新创建的托管式文件夹来验证它们,请执行以下操作: storage.objects.list
  • 如需列出托管式文件夹,请执行以下操作: storage.managedFolders.list
  • 如需获取托管式文件夹,请执行以下操作: storage.managedFolders.get
  • 如需移动托管式文件夹,请按以下步骤操作:
    • storage.managedFolders.delete(针对源存储桶)
    • storage.managedFolders.create(针对目标存储桶)
  • 如需删除托管式文件夹,请执行以下操作: storage.managedFolders.delete

如需了解如何授予存储桶的角色,请参阅将 IAM 与存储桶搭配使用

创建托管文件夹

控制台

使用 Google Cloud 控制台时,您可以通过启用对文件夹或模拟文件夹的管理来创建托管式文件夹。以下步骤介绍了如何创建文件夹或模拟文件夹,然后启用文件夹管理:

  1. 在 Google Cloud 控制台中,进入 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击要在其中创建托管文件夹的存储桶的名称。

  3. 存储桶详情页面中,点击创建文件夹以创建新文件夹。如果要转换为托管文件夹的文件夹已存在,请跳到描述如何访问更多选项 菜单的步骤。

  4. 名称字段中,为文件夹输入名称。如需了解命名注意事项,请参阅托管文件夹名称

  5. 点击创建

    新创建的文件夹会显示在文件夹浏览器窗格中。

  6. 文件夹浏览器窗格中,点击要转换为托管文件夹的文件夹旁边的更多选项 菜单,然后点击修改访问权限

    此时会显示要启用文件夹管理吗?对话框。

  7. 点击启用

    您的文件夹会转换为托管文件夹。此时会显示 MANAGED_FOLDER_NAME 的权限窗格,其中按主账号和角色显示该文件夹的 IAM 政策。如需创建新的 IAM 政策,请参阅在托管文件夹上设置 IAM 政策

命令行

如需创建托管文件夹,请运行 gcloud storage managed-folders create 命令

gcloud storage managed-folders create gs://BUCKET_NAME/MANAGED_FOLDER_NAME

其中:

  • BUCKET_NAME 是要创建托管文件夹的存储桶的名称。例如 my-bucket

  • MANAGED_FOLDER_NAME 是要创建的托管文件夹的名称。例如 my-managed-folder/

如需确认托管文件夹已创建,请运行 gcloud storage managed-folders describe 命令:

gcloud storage managed-folders describe gs://BUCKET_NAME/MANAGED_FOLDER_NAME

其中:

  • BUCKET_NAME 是已创建托管文件夹的存储桶的名称。

  • MANAGED_FOLDER_NAME 是已创建的托管文件夹的名称。

客户端库

C++

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

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

C#

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

public class StorageControlCreateManagedFolderSample
{
    public ManagedFolder StorageControlCreateManagedFolder(string bucketId = "your-unique-bucket-name",
        string managedFolderId = "your_managed_folder_id")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        ManagedFolder managedFolder = storageControl.CreateManagedFolder(
            // Set project to "_" to signify globally scoped bucket
            new BucketName("_", bucketId),
            new ManagedFolder(),
            managedFolderId
        );

        Console.WriteLine($"Managed Folder {managedFolderId} created in bucket {bucketId}");
        return managedFolder;
    }
}

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

// createManagedFolder creates a managed folder in the bucket with the given name.
func createManagedFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "managed-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()
	mf := &controlpb.ManagedFolder{}

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

	fmt.Fprintf(w, "created Managed 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.CreateManagedFolderRequest;
import com.google.storage.control.v2.ManagedFolder;
import com.google.storage.control.v2.StorageControlClient;

public class CreateManagedFolder {
  public static void managedFolderCreate(String bucketName, String managedFolderId)
      throws Exception {

    // Instantiates a client in a try-with-resource to automatically cleanup underlying resources
    try (StorageControlClient storageControlClient = StorageControlClient.create()) {
      CreateManagedFolderRequest request =
          CreateManagedFolderRequest.newBuilder()
              // Set project to "_" to signify global bucket
              .setParent(BucketName.format("_", bucketName))
              .setManagedFolder(ManagedFolder.newBuilder().build())
              .setManagedFolderId(managedFolderId)
              .build();
      String response = storageControlClient.createManagedFolder(request).getName();
      System.out.printf("Performed createManagedFolder request for %s%n", response);
    }
  }
}

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 managed folder to be created
// const managedFolderName = 'managedFolderName';

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

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

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

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

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

callCreateManagedFolder();

PHP

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\CreateManagedFolderRequest;
use Google\Cloud\Storage\Control\V2\ManagedFolder;

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

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

    // $request = new CreateManagedFolderRequest([
    //     'parent' => $formattedName,
    //     'managedFolder' => new ManagedFolder(),
    //     'managedFolderId' => $managedFolderId,
    // ]);
    $request = CreateManagedFolderRequest::build($formattedName, new ManagedFolder(), $managedFolderId);

    $managedFolder = $storageControlClient->createManagedFolder($request);

    printf('Performed createManagedFolder request for %s', $managedFolder->getName());
}

Python

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

from google.cloud import storage_control_v2


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

    # The name of the managed folder to be created
    # managed_folder_id = "managed-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.CreateManagedFolderRequest(
        parent=bucket_path,
        managed_folder_id=managed_folder_id,
    )
    response = storage_control_client.create_managed_folder(request=request)

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

Ruby

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

  # The name of the managed folder to be created
  # managed_folder_id = "managed-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::CreateManagedFolderRequest.new parent: bucket_path,
                                                                                managed_folder_id: managed_folder_id

  response = storage_control.create_managed_folder request

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

REST API

JSON API

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

  2. 使用 cURL 通过 POST ManagedFolder 请求调用 JSON API

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -d '{ "name": "MANAGED_FOLDER_NAME" }' \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders"

    其中:

    • BUCKET_NAME 是要创建托管文件夹的存储桶的名称。例如 my-bucket

    • MANAGED_FOLDER_NAME 是要创建的托管文件夹的名称。例如 my-managed-folder/

列出托管文件夹

控制台

  1. 在 Google Cloud 控制台中,进入 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 文件夹浏览器窗格中,使用切换节点 展开存储桶中的文件夹列表。

一个列表会显示存储桶中的文件夹、模拟文件夹和托管式文件夹。

命令行

如需列出托管文件夹,请运行 gcloud storage managed-folders list 命令

gcloud storage managed-folders list gs://BUCKET_NAME

其中:

  • BUCKET_NAME 是包含要列出的托管文件夹的存储桶的名称。例如 my-bucket

请注意,您也可以指定文件夹路径而不是存储桶名称。例如:

gcloud storage managed-folders list gs://my-bucket/folder/

客户端库

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 managed_folder : client.ListManagedFolders(parent)) {
    if (!managed_folder) throw std::move(managed_folder).status();
    std::cout << managed_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 StorageControlListManagedFoldersSample
{
    public IEnumerable<ManagedFolder> StorageControlListManagedFolders(string bucketId = "your-unique-bucket-name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        // Use "_" for project ID to signify globally scoped bucket
        BucketName bucketResourceName = new BucketName("_", bucketId);
        var managedFolders = storageControl.ListManagedFolders(bucketResourceName);

        foreach (var managedFolder in managedFolders)
        {
            Console.Write(managedFolder.Name);
        }
        return managedFolders;
    }
}

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

// listManagedFolders lists all managed folders present in the bucket.
func listManagedFolders(w io.Writer, bucket string) error {
	// bucket := "bucket-name"
	// folder := "managed-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.ListManagedFoldersRequest{
		Parent: bucketPath,
	}
	it := client.ListManagedFolders(ctx, req)
	for {
		f, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListManagedFolders(%q): %w", bucketPath, err)
		}
		fmt.Fprintf(w, "got managed 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.ListManagedFoldersRequest;
import com.google.storage.control.v2.ManagedFolder;
import com.google.storage.control.v2.StorageControlClient;

class ListManagedFolders {

  public static void managedFolderList(String bucketName) throws Exception {
    // Instantiates a client in a try-with-resource to automatically cleanup underlying resources
    try (StorageControlClient storageControlClient = StorageControlClient.create()) {
      ListManagedFoldersRequest listManagedFoldersRequest =
          ListManagedFoldersRequest.newBuilder()
              // Set project to "_" to signify global bucket
              .setParent(BucketName.format("_", bucketName))
              .build();
      Iterable<ManagedFolder> managedFolders =
          storageControlClient.listManagedFolders(listManagedFoldersRequest).iterateAll();
      for (ManagedFolder folder : managedFolders) {
        System.out.printf("%s bucket has managed folder %s%n", bucketName, 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 callListManagedFolders() {
  const bucketPath = controlClient.bucketPath('_', bucketName);

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

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

callListManagedFolders();

PHP

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

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

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

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

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

    foreach ($folders as $folder) {
        printf('%s bucket has managed folder %s' . PHP_EOL, $bucketName, $folder->getName());
    }
}

Python

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

from google.cloud import storage_control_v2


def list_managed_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.ListManagedFoldersRequest(
        parent=bucket_path,
    )

    page_result = storage_control_client.list_managed_folders(request=request)
    for managed_folder in page_result:
        print(managed_folder)

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

Ruby

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

def list_managed_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::ListManagedFoldersRequest.new parent: bucket_path

  managed_folders = storage_control.list_managed_folders request
  managed_folders.each do |managed_folder|
    puts managed_folder
  end

  puts "Listed managed folders in bucket #{bucket_name}"
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/managedFolders"

    其中,BUCKET_NAME 是包含要列出的托管式文件夹的存储桶的名称。例如 my-bucket

获取托管式文件夹的元数据

命令行

如需获取托管式文件夹的元数据,请运行 gcloud storage managed-folders describe 命令

  gcloud storage managed-folders describe gs://BUCKET_NAME/MANAGED_FOLDER_NAME

其中:

  • BUCKET_NAME 是包含要列出的托管文件夹的存储桶的名称。例如 my-bucket

  • MANAGED_FOLDER_NAME 是要检索元数据的托管式文件夹的名称。

客户端库

C++

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

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

C#

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

public class StorageControlGetManagedFolderSample
{
    public ManagedFolder StorageControlGetManagedFolder(string bucketId = "your-unique-bucket-name",
        string managedFolderId = "your_managed_folder_Id")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        ManagedFolderName managedFolderResourceName =
            // Set project to "_" to signify globally scoped bucket
            new ManagedFolderName("_", bucketId, managedFolderId);

        ManagedFolder managedFolder = storageControl.GetManagedFolder(managedFolderResourceName);

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

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

// getManagedFolder gets metadata for the managed folder with the given name.
func getManagedFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "managed-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/managedFolders/%v/", bucket, folder)

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

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

Java

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证


import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.GetManagedFolderRequest;
import com.google.storage.control.v2.ManagedFolder;
import com.google.storage.control.v2.ManagedFolderName;
import com.google.storage.control.v2.StorageControlClient;

class GetManagedFolder {

  public static void managedFolderGet(String bucketName, String managedFolderId) throws Exception {
    // Instantiates a client in a try-with-resource to automatically cleanup underlying resources
    try (StorageControlClient storageControlClient = StorageControlClient.create()) {
      // Set project to "_" to signify global bucket
      BucketName resourceBucketName = BucketName.of("_", bucketName);
      GetManagedFolderRequest getManagedFolderRequest =
          GetManagedFolderRequest.newBuilder()
              .setName(
                  ManagedFolderName.format(
                      resourceBucketName.getProject(),
                      resourceBucketName.getBucket(),
                      managedFolderId))
              .build();
      ManagedFolder managedFolder = storageControlClient.getManagedFolder(getManagedFolderRequest);
      System.out.printf("Got Managed Folder %s%n", managedFolder.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 managed folder to get
// const managedFolderName = 'managedFolderName';

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

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

async function callGetManagedFolder() {
  const managedFolderPath = controlClient.managedFolderPath(
    '_',
    bucketName,
    managedFolderName
  );

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

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

callGetManagedFolder();

PHP

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

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

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

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

    $managedFolder = $storageControlClient->getManagedFolder($request);

    printf('Got Managed Folder %s', $managedFolder->getName());
}

Python

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

from google.cloud import storage_control_v2


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

    # The name of the managed folder
    # managed_folder_id = "managed-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.managed_folder_path(
        "_", bucket_name, managed_folder_id
    )

    request = storage_control_v2.GetManagedFolderRequest(
        name=folder_path,
    )
    response = storage_control_client.get_managed_folder(request=request)

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

Ruby

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

  # The name of the managed folder to be created
  # managed_folder_id = "managed-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.
  folder_path = storage_control.managed_folder_path project: "_",
                                                    bucket: bucket_name,
                                                    managed_folder: managed_folder_id

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

  response = storage_control.get_managed_folder request

  puts "Got managed folder: #{response.name}"
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/managedFolders/MANAGED_FOLDER_NAME"

    其中:

    • BUCKET_NAME 是包含要获取的托管式文件夹的存储桶的名称。例如 my-bucket

    • MANAGED_FOLDER_NAME 是托管式文件夹的名称,以路径表示。例如 example-dir/。如果托管式文件夹是嵌套的,则必须转义托管式文件夹路径中的斜杠 (/) 字符。例如 example-dir1%2Fexample-dir2

移动托管文件夹

控制台

  1. 在目标存储桶中创建新的托管文件夹

  2. 将源存储桶中的原始托管文件夹的 IAM 政策复制到目标存储桶中的新托管文件夹。

  3. 将源存储桶中的原始托管文件夹中的对象复制到目标存储桶中的新托管文件夹。

  4. 从源存储桶中删除原始托管文件夹

命令行

如需移动托管文件夹及其包含的对象,请运行带有 --include-managed-folders 选项的 gcloud storage mv 命令

gcloud storage mv --include-managed-folders gs://SOURCE_BUCKET_NAME/MANAGED_FOLDER_NAME gs://DESTINATION_BUCKET_NAME/MANAGED_FOLDER_NAME

其中:

  • SOURCE_BUCKET 是原始存储桶的名称,例如 my-source-bucket

  • DESTINATION_BUCKET 是托管文件夹要移动到的存储桶的名称。例如 my-destination-bucket

  • MANAGED_FOLDER_NAME 是要移动的托管文件夹的名称。例如 my-managed-folder/

REST API

JSON API

如需将托管文件夹从一个存储桶移动到另一个存储桶,请完成以下步骤:

  1. 在目标存储桶中创建新的托管文件夹

  2. 将源存储桶中的原始托管文件夹的 IAM 政策复制到目标存储桶中的新托管文件夹。

  3. 将源存储桶中的原始托管文件夹中的对象复制到目标存储桶中的新托管文件夹。

  4. 从源存储桶中删除原始托管文件夹

删除托管文件夹

控制台

  1. 在 Google Cloud 控制台中,进入 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击包含待删除托管式文件夹的存储桶的名称。

  3. 存储桶详情页面中,点击要删除的托管文件夹旁边的更多选项图标

  4. 点击删除文件夹

  5. 如需确认要删除托管文件夹,请在删除字段中输入 DELETE

  6. 点击删除

    托管文件夹及其内容(包括存储的对象和其他托管文件夹)会从 Cloud Storage 存储桶中删除。

命令行

如需删除托管文件夹及其包含的对象,请运行 gcloud storage rm 命令

gcloud storage rm -r gs://BUCKET_NAME/MANAGED_FOLDER_NAME

其中:

  • BUCKET_NAME 是包含要删除的托管文件夹的存储桶的名称。例如 my-bucket

  • MANAGED_FOLDER_NAME 是要删除的托管文件夹的名称。例如 my-managed-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& managed_folder_id) {
  auto const name = std::string{"projects/_/buckets/"} + bucket_name +
                    "/managedFolders/" + managed_folder_id;
  auto status = client.DeleteManagedFolder(name);
  if (!status.ok()) throw std::move(status);

  std::cout << "Deleted managed folder: " << managed_folder_id << "\n";
}

C#

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

public class StorageControlDeleteManagedFolderSample
{
    public void StorageControlDeleteManagedFolder(string bucketId = "your-unique-bucket-name",
        string managedFolderId = "your_managed_folder_id")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        ManagedFolderName managedFolderResourceName =
            // Set project to "_" to signify globally scoped bucket
            new ManagedFolderName("_", bucketId, managedFolderId);

        storageControl.DeleteManagedFolder(managedFolderResourceName);

        Console.WriteLine($"Deleted managed folder {managedFolderId} from bucket {bucketId}");
    }
}

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

// deleteManagedFolder deletes the managed folder with the given name.
func deleteManagedFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "managed-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/managedFolders/%v/", bucket, folder)

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

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

Java

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.DeleteManagedFolderRequest;
import com.google.storage.control.v2.ManagedFolderName;
import com.google.storage.control.v2.StorageControlClient;

class DeleteManagedFolder {
  public static void managedFolderDelete(String bucketName, String managedFolderId)
      throws Exception {
    // Instantiates a client in a try-with-resource to automatically cleanup underlying resources
    try (StorageControlClient storageControlClient = StorageControlClient.create()) {
      // Set project to "_" to signify global bucket
      BucketName resourceBucketName = BucketName.of("_", bucketName);
      DeleteManagedFolderRequest deleteManagedFolderRequest =
          DeleteManagedFolderRequest.newBuilder()
              .setName(
                  ManagedFolderName.format(
                      resourceBucketName.getProject(),
                      resourceBucketName.getBucket(),
                      managedFolderId))
              .build();
      storageControlClient.deleteManagedFolder(deleteManagedFolderRequest);
      System.out.printf("Deleted Managed Folder %s%n", managedFolderId);
    }
  }
}

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 managedFolderName = 'managedFolderName';

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

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

async function callDeleteManagedFolder() {
  const managedFolderPath = controlClient.managedFolderPath(
    '_',
    bucketName,
    managedFolderName
  );

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

  // Run request
  await controlClient.deleteManagedFolder(request);
  console.log(`Deleted managed folder: ${managedFolderName}.`);
}

callDeleteManagedFolder();

PHP

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

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

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

    $request = DeleteManagedFolderRequest::build($formattedName);

    $storageControlClient->deleteManagedFolder($request);

    printf('Deleted Managed Folder %s', $managedFolderId);
}

Python

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

from google.cloud import storage_control_v2


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

    # The name of the managed folder to be deleted
    # managed_folder_id = "managed-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.managed_folder_path(
        "_", bucket_name, managed_folder_id
    )

    request = storage_control_v2.DeleteManagedFolderRequest(
        name=folder_path,
    )
    storage_control_client.delete_managed_folder(request=request)

    print(f"Deleted managed folder: {managed_folder_id}")

Ruby

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

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

  # The name of the managed folder to be created
  # managed_folder_id = "managed-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.
  folder_path = storage_control.managed_folder_path project: "_",
                                                    bucket: bucket_name,
                                                    managed_folder: managed_folder_id

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

  storage_control.delete_managed_folder request

  puts "Deleted managed folder: #{managed_folder_id}"
end

REST API

JSON API

如需删除托管文件夹,您必须先删除托管文件夹中的对象

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

  2. 使用 cURL 通过 DELETE ManagedFolder 请求调用 JSON API

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

    其中:

    • BUCKET_NAME 是包含要删除的托管文件夹的存储桶的名称。例如 my-bucket

    • MANAGED_FOLDER_NAME 是要删除的托管文件夹的名称。例如 my-managed-folder/

    默认情况下,托管文件夹必须为空,然后才能删除。如需删除非空托管文件夹,请在请求中添加 allowNonEmpty=true 作为查询参数。

问题排查

如需获得创建和管理托管文件夹方面的帮助,请参阅问题排查页面

后续步骤