创建和管理文件夹

本页面介绍了如何在启用了分层命名空间的存储桶中创建、列出和删除文件夹以及获取其元数据。

创建文件夹

本部分介绍如何创建文件夹。

控制台

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

    进入“存储桶”

  2. 在存储桶列表中,点击要在其中创建文件夹的存储桶的名称。
  3. 存储桶详情页面中,点击创建文件夹以创建一个空文件夹。
  4. 名称字段中,为文件夹输入名称。如需了解命名注意事项,请参阅注意事项
  5. 点击创建

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

命令行

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

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 标头生成访问令牌。

    或者,您可以使用 OAuth 2.0 Playground 创建访问令牌,并将其包含在 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 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击您要列出其文件夹的存储桶的名称。

  3. 文件夹浏览器窗格中,使用展开箭头 展开存储桶中的文件夹列表。

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

命令行

如需列出存储桶中的所有文件夹,请运行以下命令:

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

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 标头生成访问令牌。

    或者,您可以使用 OAuth 2.0 Playground 创建访问令牌,并将其包含在 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 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击要删除文件夹的存储桶的名称。

  3. 文件夹浏览器窗格中,使用展开箭头 展开存储桶中的文件夹列表。

  4. 找到要删除的文件夹。

  5. 点击文件夹的 更多操作菜单。

  6. 点击删除文件夹

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

  8. 点击删除

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

命令行

如需删除空文件夹,请运行以下命令:

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

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 标头生成访问令牌。

    或者,您可以使用 OAuth 2.0 Playground 创建访问令牌,并将其包含在 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 是要删除的文件夹的网址编码名称。例如,my-folder/ 的网址编码为 my-folder%2F

获取文件夹的元数据

本部分介绍了如何获取文件夹的元数据。

命令行

如需获取文件夹的元数据,请运行以下命令:

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

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 标头生成访问令牌。

    或者,您可以使用 OAuth 2.0 Playground 创建访问令牌,并将其包含在 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. 在您创建的托管式文件夹上设置和管理 Identity and Access Management (IAM) 政策

后续步骤

自行试用

如果您是 Google Cloud 新手,请创建一个账号来评估 Cloud Storage 在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。

免费试用 Cloud Storage