建立及管理資料夾

本頁說明如何建立、列出、上傳、刪除 bucket 中的資料夾,以及取得這些資料夾的中繼資料,前提是 bucket 已啟用階層式命名空間

事前準備

確認 bucket 已啟用階層命名空間。如需在 bucket 上啟用階層式命名空間的詳細操作說明,請參閱「建立已啟用階層式命名空間的 bucket」。

建立資料夾

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

控制台

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

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下要建立資料夾的值區名稱。
  3. 在「Bucket details」(值區詳細資料) 頁面中,按一下「Create folder」(建立資料夾) 建立空白資料夾。
  4. 在「Name」(名稱) 欄位中,輸入資料夾名稱。如需命名注意事項,請參閱「注意事項」。
  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 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
  3. 用戶端程式庫

    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 bucket」頁面。

    前往「Buckets」(值區) 頁面

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

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

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

指令列

如要列出 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

上傳資料夾

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

控制台

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

    前往「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 bucket」頁面。

    前往「Buckets」(值區) 頁面

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

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

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

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

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

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

  8. 點選「刪除」。

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

指令列

如要刪除空白資料夾,請執行 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 是要刪除的資料夾名稱 (經過網址編碼)。例如 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