存储控制创建托管文件夹

存储控制创建托管文件夹

深入探索

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

代码示例

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

后续步骤

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