使用物件內容

本頁說明如何以鍵/值配對的形式,在 Cloud Storage 物件上附加及管理內容

取得必要角色

如要取得建立及管理物件內容所需的權限,請要求管理員在物件上授予下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這些預先定義的角色具備建立及管理物件內容所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要建立及管理物件內容,必須具備下列權限:

  • 建立含有物件內容的物件:
    • storage.objects.create
    • storage.objects.createContext
  • 附加、更新及刪除物件內容:
    • storage.objects.update
    • storage.objects.createContext
    • storage.objects.updateContext
    • storage.objects.deleteContext
  • 查看物件內容:
    • storage.objects.get
    • storage.objects.list

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

將內容附加至新物件

將新物件上傳至 Cloud Storage 值區時,請將內容附加至物件。每個內容都包含鍵和值。

指令列

如要使用 gcloud alpha storage cp 指令上傳物件時附加內容,請使用 --custom-contexts 旗標:

gcloud alpha storage cp OBJECT_LOCATION gs://DESTINATION_BUCKET_NAME --custom-contexts=KEY=VALUE,...

其中:

  • OBJECT_LOCATION 是物件的本機路徑。例如:Desktop/dog.png
  • DESTINATION_BUCKET_NAME 是您要向其上傳物件的值區名稱。例如:my-bucket
  • KEY 是要附加至物件的內容鍵。例如,Department。您可以指定多個以半形逗號分隔的鍵/值組合。
  • VALUE 是要與內容鍵建立關聯的值。例如:Human resources

或者,建立包含要附加至物件的內容的 JSON 檔案,並使用 --custom-contexts-file 旗標:

  {
    "KEY": {
      "value": "VALUE"
    },
    ...
  }

其中:

  • KEY 是要附加至物件的內容鍵。例如,Department。您可以指定多個鍵/值組合。
  • VALUE 是要與內容鍵建立關聯的值。例如:Human resources

如要在使用 gcloud alpha storage rsync 指令上傳目錄時附加內容,請使用 --custom-contexts 旗標或 --custom-contexts-file 旗標:

gcloud alpha storage rsync DIRECTORY_LOCATION gs://DESTINATION_BUCKET_NAME --recursive --custom-contexts=KEY=VALUE,...

其中:

  • DIRECTORY_LOCATION 是目錄的本機路徑。例如:~/my_directory
  • DESTINATION_BUCKET_NAME 是您要上傳目錄的值區名稱。例如:my-bucket
  • KEY 是要附加至物件的情境鍵。例如,Department。您可以指定多個以半形逗號分隔的鍵/值組合。
  • VALUE 是要與內容鍵建立關聯的值。例如:Human resources

JSON API

如要在上傳新物件時將背景資訊附加至物件,請使用下列任一方法:

以 JSON 格式提供物件中繼資料時,請加入 contexts 欄位:

  {
    "contexts": {
      "custom": {
        "KEY": {
          "value": "VALUE"
        },
        ...
      }
    }
  }

其中:

  • KEY 是要附加至物件的內容鍵。例如,Department。您可以在 custom 物件中指定多個鍵/值組合。
  • VALUE 是要與內容鍵建立關聯的值。例如:Human resources

將情境附加至現有物件或修改情境

您可以將新內容附加至 Cloud Storage bucket 中的現有物件。

指令列

使用 gcloud alpha storage objects update 指令:

gcloud alpha storage objects update gs://BUCKET_NAME/OBJECT_NAME CUSTOM_CONTEXTS_FLAG

其中:

  • BUCKET_NAME 是值區名稱,其中包含您要編輯內容的物件。例如:my-bucket
  • OBJECT_NAME 是物件的名稱。例如:pets/dog.png
  • CUSTOM_CONTEXTS_FLAG 是下列任何一個標記:

    • 如要取代所有現有內容,請使用 --custom-contexts=KEY=VALUE,...--custom-contexts-file=CUSTOM_CONTEXTS_FILE

      其中:

      • KEY 是要附加至物件的內容鍵。例如,Department。您可以指定多個以半形逗號分隔的鍵值組。
      • VALUE 是要與內容鍵建立關聯的值。例如:Human resources
      • CUSTOM_CONTEXTS_FILE 是 JSON 或 YAML 檔案的路徑,其中包含要附加至物件的內容。
    • 如要刪除所有現有內容,請使用 --clear-custom-contexts

    • 如要新增、修改或刪除個別內容,請同時使用 --update-custom-contexts=KEY=VALUE,...--remove-custom-contexts=KEY,...

      其中:

      • KEY 是要附加至物件或從物件刪除的內容鍵。例如:Department
      • VALUE 是要與您想附加至物件的內容鍵建立關聯的值。例如:Human resources

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

Patching gs://my-bucket/pets/dog.png#1560574162144861...
  Completed 1

用戶端程式庫

Java

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

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


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.BlobInfo.ObjectContexts;
import com.google.cloud.storage.BlobInfo.ObjectCustomContextPayload;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.collect.Maps;
import java.util.Map;

public class SetObjectContexts {
  public static void setObjectContexts(
      String projectId, String bucketName, String objectName, String key, String value)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The context key-value you want to add
    // String key = "your-context-key";
    // String value = "your-context-value";

    try (Storage storage =
        StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
      BlobId blobId = BlobId.of(bucketName, objectName);
      Blob blob = storage.get(blobId);
      if (blob == null) {
        System.out.println("The object " + objectName + " was not found in " + bucketName);
        return;
      }

      // Recommended: Set a generation-match precondition to avoid potential race
      // conditions and data corruptions. The request to update returns a 412 error if
      // the object's generation number does not match your precondition.
      Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();

      // This section demonstrates how to upsert, delete all, and delete a specific context.

      // To upsert a context (if the key already exists, its value is replaced;
      // otherwise, a new key-value pair is added):
      ObjectCustomContextPayload payload =
          ObjectCustomContextPayload.newBuilder().setValue(value).build();
      Map<String, ObjectCustomContextPayload> custom = Maps.newHashMap();
      custom.put(key, payload);
      ObjectContexts contexts = ObjectContexts.newBuilder().setCustom(custom).build();

      /*
       * To delete all existing contexts:
       * ObjectContexts contexts = ObjectContexts.newBuilder().setCustom(null).build();
       */

      /*
       * To delete a specific key from the context:
       * Map<String, ObjectCustomContextPayload> custom = Maps.newHashMap();
       * custom.put(key, null);
       * ObjectContexts contexts = ObjectContexts.newBuilder().setCustom(custom).build();
       */
      BlobInfo pendingUpdate = blob.toBuilder().setContexts(contexts).build();
      storage.update(pendingUpdate, precondition);

      System.out.println(
          "Updated custom contexts for object " + objectName + " in bucket " + bucketName);
    }
  }
}

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立包含物件設定的 JSON 檔案,其中必須包含物件的 contexts 設定欄位。

    如要新增、修改或覆寫現有內容,請使用下列格式:

      {
        "contexts": {
          "custom": {
            "KEY": {
              "value": "VALUE"
            },
            ...
          }
        }
      }

    其中:

    • KEY 是要附加至物件的內容鍵。例如,Department。您可以在 custom 物件中指定多個鍵/值組合。
    • VALUE 是要與內容鍵建立關聯的值。例如:Human resources

    如要刪除所有現有內容,請使用下列格式:

      {
        "contexts": {
          "custom": null
        }
      }

    如要從背景資訊刪除特定鍵,請使用下列格式:

      {
        "contexts": {
          "custom": {
            "KEY": null,
            ...
          }
        }
      }

    其中:

    KEY 是要從物件刪除的內容鍵。例如:Department。您可以指定要從 custom 物件刪除的多個鍵。

  3. 使用 cURL 透過 PATCH 物件要求呼叫 JSON API

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage./storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"

    其中:

    • JSON_FILE_NAME 是包含物件內容資訊的檔案路徑。
    • BUCKET_NAME 是值區名稱,其中包含您要編輯內容的物件。例如:my-bucket
    • OBJECT_NAME 是物件的網址編碼名稱。舉例來說,pets/dog.png 經過網址編碼後會變成 pets%2Fdog.png

或者,您也可以使用 PUT Object 要求替換物件的內容。PUT 物件要求也會取代其他物件中繼資料。因此,我們不建議使用 PUT 物件要求。

查看物件內容

您可以列出物件中繼資料或說明特定物件,藉此查看物件的內容。

指令列

使用 gcloud alpha storage objects describe 指令:

gcloud alpha storage objects describe gs://BUCKET_NAME/OBJECT_NAME

其中:

  • BUCKET_NAME 是值區名稱,其中包含您要查看內容的物件。例如:my-bucket
  • OBJECT_NAME 是您要查看內容的物件名稱。例如:pets/dog.png

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

bucket: my-bucket
contexts:
  Department:
    createTime: '2023-01-01T00:00:00.000000+00:00'
    type: CUSTOM
    updateTime: '2023-01-01T00:00:00.000000+00:00'
    value: HR
  DataClassification:
    createTime: '2023-01-01T00:00:00.000000+00:00'
    type: CUSTOM
    updateTime: '2023-01-01T00:00:00.000000+00:00'
    value: Confidential
name: employees.txt

用戶端程式庫

Java

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

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


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo.ObjectContexts;
import com.google.cloud.storage.BlobInfo.ObjectCustomContextPayload;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class GetObjectContexts {
  public static void getObjectContexts(String projectId, String bucketName, String objectName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    try (Storage storage =
        StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {

      Blob blob = storage.get(bucketName, objectName);
      if (blob == null) {
        System.out.println("The object " + objectName + " was not found in " + bucketName);
        return;
      }
      ObjectContexts objectContexts = blob.getContexts();

      if (objectContexts != null) {
        Map<String, ObjectCustomContextPayload> customContexts = objectContexts.getCustom();
        if (customContexts == null) {
          System.out.println("No custom contexts found for object: " + objectName);
          return;
        }
        // Print blob's object contexts
        System.out.println("\nCustom Contexts:");
        for (Map.Entry<String, ObjectCustomContextPayload> custom : customContexts.entrySet()) {
          System.out.println(custom.getKey() + "=" + custom.getValue());
        }
      }
    }
  }
}

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 GET 物件要求呼叫 JSON API

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

    其中:

    • BUCKET_NAME 是值區名稱,其中包含您要查看內容的物件。例如:my-bucket
    • OBJECT_NAME 是您要查看內容的物件名稱,並經過網址編碼。例如 pets/dog.png,網址編碼為 pets%2Fdog.png

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

      {
        "kind": "storage#object",
        "name": "employees.txt",
        "bucket": "my-bucket",
        "contexts": {
          "custom": {
            "Department": {
              "value": "HR",
              "createTime": "2023-01-01T00:00:00.000Z",
              "updateTime": "2023-01-01T00:00:00.000Z"
            },
            "DataClassification": {
              "value": "Confidential",
              "createTime": "2023-01-01T00:00:00.000Z",
              "updateTime": "2023-01-01T00:00:00.000Z"
            }
          }
        }
      }
      

依據情境篩選物件

依物件內容鍵是否存在或特定值篩選物件。依內容篩選物件,有助於有效率地找出及管理特定物件群組。詳情請參閱「依環境篩選物件」。

在物件作業期間管理物件內容

複製、重寫、組合、移動或還原物件時,物件內容預設會保留。您也可以在複製、重寫和撰寫作業期間修改內容。

指令列

根據預設,gcloud alpha storage cp 指令、gcloud alpha storage rsync 指令和 gcloud alpha storage mv 指令會保留來源物件的內容。如要在這些作業期間修改內容,請使用下列任一標記:

  • --custom-contexts--custom-contexts-file 旗標,可為目的地物件設定新的環境。
  • --clear-custom-contexts 標記,可防止來源物件的內容附加至目的地物件。
  • 結合 --update-custom-contexts--remove-custom-contexts 標記,在將個別內容附加至目的地物件前,先從來源物件修改這些內容。

gcloud alpha storage objects compose 指令會合併來源物件的內容,並預設將內容附加至目的地物件。Cloud Storage 會優先處理稍後處理的來源物件,藉此解決衝突。如要進一步瞭解組合作業期間的物件內容行為,請參閱複合物件內容。您也可以使用 --custom-contexts--custom-contexts-file 標記,為目的地物件指定新內容。

JSON API

  • 如要在 複製重寫物件作業期間修改背景資訊,請在要求主體中加入 contexts.custom 屬性。如果未加入這項屬性,系統預設會保留來源物件的環境。

  • 撰寫物件時,來源物件的內容會預設合併至目的地物件。Cloud Storage 會優先處理稍後處理的來源物件內容,藉此解決衝突。如要進一步瞭解組合作業期間的物件內容行為,請參閱「複合物件內容」。您也可以在 destination.contexts.custom 屬性中,為目的地物件指定新內容。

後續步驟