查看及編輯物件中繼資料

本頁面說明如何查看和編輯存於 Cloud Storage 中與物件相關的中繼資料。如需物件中繼資料的總覽,請參閱物件中繼資料一文。

本頁面並未討論如何查看或編輯身分與存取權管理 (IAM) 政策,也未討論物件存取控制清單 (ACL),這兩者可以控管哪些使用者有權存取您的資料。如需相關的工作指南,請參閱使用 IAM 權限建立和管理 ACL 相關頁面。

查看物件中繼資料

如何查看與物件相關的中繼資料:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,找到包含所需物件的值區名稱,然後點選這個名稱,前往該物件的所在位置。

    物件中繼資料的部分資訊 (例如物件大小和儲存空間級別) 會與物件名稱一併顯示。

  3. 按一下和物件相關的 [more options] (更多選項) 按鈕 (更多動作圖示。)。

  4. 按一下 [Edit metadata] (編輯中繼資料)。

    物件目前的可編輯中繼資料值會顯示在隨即出現的重疊視窗中。

gsutil

使用 gsutil ls -L 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

gsutil ls -L  gs://[BUCKET_NAME]/[OBJECT_NAME]

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

gs://my-awesome-bucket/cat.jpeg:
Creation time:          Fri, 03 Feb 2017 22:43:31 GMT
Update time:            Wed, 10 May 2017 18:33:07 GMT
Storage class:          REGIONAL
Content-Length:         11012
Content-Type:           image/jpeg
Metadata:
    Breed:              Tabby
Hash (crc32c):          HQbzrB==
Hash (md5):             OBydg25+pPG1Cwawjsl7DA==
ETag:                   CJCh9apA9dECAEs=
Generation:             1486161811706000
Metageneration:         11

如果您擁有充足的權限,也會看見物件的存取控制清單。

程式碼範例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.GetObjectMetadata(bucket_name, object_name);

  if (!object_metadata) {
    throw std::runtime_error(object_metadata.status().message());
  }

  std::cout << "The metadata for object " << object_metadata->name()
            << " in bucket " << object_metadata->bucket() << " is "
            << *object_metadata << "\n";
}
%}

C#

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

private void GetMetadata(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    Console.WriteLine($"Bucket:\t{storageObject.Bucket}");
    Console.WriteLine($"CacheControl:\t{storageObject.CacheControl}");
    Console.WriteLine($"ComponentCount:\t{storageObject.ComponentCount}");
    Console.WriteLine($"ContentDisposition:\t{storageObject.ContentDisposition}");
    Console.WriteLine($"ContentEncoding:\t{storageObject.ContentEncoding}");
    Console.WriteLine($"ContentLanguage:\t{storageObject.ContentLanguage}");
    Console.WriteLine($"ContentType:\t{storageObject.ContentType}");
    Console.WriteLine($"Crc32c:\t{storageObject.Crc32c}");
    Console.WriteLine($"ETag:\t{storageObject.ETag}");
    Console.WriteLine($"Generation:\t{storageObject.Generation}");
    Console.WriteLine($"Id:\t{storageObject.Id}");
    Console.WriteLine($"Kind:\t{storageObject.Kind}");
    Console.WriteLine($"KmsKeyName:\t{storageObject.KmsKeyName}");
    Console.WriteLine($"Md5Hash:\t{storageObject.Md5Hash}");
    Console.WriteLine($"MediaLink:\t{storageObject.MediaLink}");
    Console.WriteLine($"Metageneration:\t{storageObject.Metageneration}");
    Console.WriteLine($"Name:\t{storageObject.Name}");
    Console.WriteLine($"Size:\t{storageObject.Size}");
    Console.WriteLine($"StorageClass:\t{storageObject.StorageClass}");
    Console.WriteLine($"TimeCreated:\t{storageObject.TimeCreated}");
    Console.WriteLine($"Updated:\t{storageObject.Updated}");
    bool? eventBasedHoldOrNull = storageObject?.EventBasedHold;
    bool eventBasedHold =
        eventBasedHoldOrNull.HasValue ? eventBasedHoldOrNull.Value : false;
    Console.WriteLine("Event-based hold enabled? {0}", eventBasedHold);
    bool? temporaryHoldOrNull = storageObject?.TemporaryHold;
    bool temporaryHold =
        temporaryHoldOrNull.HasValue ? temporaryHoldOrNull.Value : false;
    Console.WriteLine("Temporary hold enabled? {0}", temporaryHold);
    Console.WriteLine($"RetentionExpirationTime\t{storageObject.RetentionExpirationTime}");
}

Go

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

o := client.Bucket(bucket).Object(object)
attrs, err := o.Attrs(ctx)
if err != nil {
	return nil, err
}
log.Printf("Bucket: %v\n", attrs.Bucket)
log.Printf("CacheControl: %v\n", attrs.CacheControl)
log.Printf("ContentDisposition: %v\n", attrs.ContentDisposition)
log.Printf("ContentEncoding: %v\n", attrs.ContentEncoding)
log.Printf("ContentLanguage: %v\n", attrs.ContentLanguage)
log.Printf("ContentType: %v\n", attrs.ContentType)
log.Printf("Crc32c: %v\n", attrs.CRC32C)
log.Printf("Generation: %v\n", attrs.Generation)
log.Printf("KmsKeyName: %v\n", attrs.KMSKeyName)
log.Printf("Md5Hash: %v\n", attrs.MD5)
log.Printf("MediaLink: %v\n", attrs.MediaLink)
log.Printf("Metageneration: %v\n", attrs.Metageneration)
log.Printf("Name: %v\n", attrs.Name)
log.Printf("Size: %v\n", attrs.Size)
log.Printf("StorageClass: %v\n", attrs.StorageClass)
log.Printf("TimeCreated: %v\n", attrs.Created)
log.Printf("Updated: %v\n", attrs.Updated)
log.Printf("Event-based hold enabled? %t\n", attrs.EventBasedHold)
log.Printf("Temporary hold enabled? %t\n", attrs.TemporaryHold)
log.Printf("Retention expiration time %v\n", attrs.RetentionExpirationTime)
log.Print("\n\nMetadata\n")
for key, value := range attrs.Metadata {
	log.Printf("\t%v = %v\n", key, value)
}

return attrs, nil

Java

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

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

// The name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

// Select all fields
// Fields can be selected individually e.g. Storage.BlobField.CACHE_CONTROL
Blob blob = storage.get(bucketName, blobName, BlobGetOption.fields(Storage.BlobField.values()));

// Print blob metadata
System.out.println("Bucket: " + blob.getBucket());
System.out.println("CacheControl: " + blob.getCacheControl());
System.out.println("ComponentCount: " + blob.getComponentCount());
System.out.println("ContentDisposition: " + blob.getContentDisposition());
System.out.println("ContentEncoding: " + blob.getContentEncoding());
System.out.println("ContentLanguage: " + blob.getContentLanguage());
System.out.println("ContentType: " + blob.getContentType());
System.out.println("Crc32c: " + blob.getCrc32c());
System.out.println("Crc32cHexString: " + blob.getCrc32cToHexString());
System.out.println("ETag: " + blob.getEtag());
System.out.println("Generation: " + blob.getGeneration());
System.out.println("Id: " + blob.getBlobId());
System.out.println("KmsKeyName: " + blob.getKmsKeyName());
System.out.println("Md5Hash: " + blob.getMd5());
System.out.println("Md5HexString: " + blob.getMd5ToHexString());
System.out.println("MediaLink: " + blob.getMediaLink());
System.out.println("Metageneration: " + blob.getMetageneration());
System.out.println("Name: " + blob.getName());
System.out.println("Size: " + blob.getSize());
System.out.println("StorageClass: " + blob.getStorageClass());
System.out.println("TimeCreated: " + new Date(blob.getCreateTime()));
System.out.println("Last Metadata Update: " + new Date(blob.getUpdateTime()));
Boolean temporaryHoldIsEnabled = (blob.getTemporaryHold() != null && blob.getTemporaryHold());
System.out.println("temporaryHold: " + (temporaryHoldIsEnabled ? "enabled" : "disabled"));
Boolean eventBasedHoldIsEnabled =
    (blob.getEventBasedHold() != null && blob.getEventBasedHold());
System.out.println("eventBasedHold: " + (eventBasedHoldIsEnabled ? "enabled" : "disabled"));
if (blob.getRetentionExpirationTime() != null) {
  System.out.println("retentionExpirationTime: " + new Date(blob.getRetentionExpirationTime()));
}
if (blob.getMetadata() != null) {
  System.out.println("\n\n\nUser metadata:");
  for (Map.Entry<String, String> userMetadata : blob.getMetadata().entrySet()) {
    System.out.println(userMetadata.getKey() + "=" + userMetadata.getValue());
  }
}

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

// Gets the metadata for the file
const [metadata] = await storage
  .bucket(bucketName)
  .file(filename)
  .getMetadata();

console.log(`File: ${metadata.name}`);
console.log(`Bucket: ${metadata.bucket}`);
console.log(`Storage class: ${metadata.storageClass}`);
console.log(`Self link: ${metadata.selfLink}`);
console.log(`ID: ${metadata.id}`);
console.log(`Size: ${metadata.size}`);
console.log(`Updated: ${metadata.updated}`);
console.log(`Generation: ${metadata.generation}`);
console.log(`Metageneration: ${metadata.metageneration}`);
console.log(`Etag: ${metadata.etag}`);
console.log(`Owner: ${metadata.owner}`);
console.log(`Component count: ${metadata.component_count}`);
console.log(`Crc32c: ${metadata.crc32c}`);
console.log(`md5Hash: ${metadata.md5Hash}`);
console.log(`Cache-control: ${metadata.cacheControl}`);
console.log(`Content-type: ${metadata.contentType}`);
console.log(`Content-disposition: ${metadata.contentDisposition}`);
console.log(`Content-encoding: ${metadata.contentEncoding}`);
console.log(`Content-language: ${metadata.contentLanguage}`);
console.log(`Media link: ${metadata.mediaLink}`);
console.log(`KMS Key Name: ${metadata.kmsKeyName}`);
console.log(`Temporary Hold: ${metadata.temporaryHold}`);
console.log(`Event-based hold: ${metadata.eventBasedHold}`);
console.log(`Effective Expiration Time: ${metadata.effectiveExpirationTime}`);
console.log(`Metadata: ${metadata.metadata}`);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * List object metadata.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 *
 * @return void
 */
function object_metadata($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $info = $object->info();
    printf('Blob: %s' . PHP_EOL, $info['name']);
    printf('Bucket: %s' . PHP_EOL, $info['bucket']);
    printf('Storage class: %s' . PHP_EOL, $info['storageClass']);
    printf('ID: %s' . PHP_EOL, $info['id']);
    printf('Size: %s' . PHP_EOL, $info['size']);
    printf('Updated: %s' . PHP_EOL, $info['updated']);
    printf('Generation: %s' . PHP_EOL, $info['generation']);
    printf('Metageneration: %s' . PHP_EOL, $info['metageneration']);
    printf('Etag: %s' . PHP_EOL, $info['etag']);
    printf('Crc32c: %s' . PHP_EOL, $info['crc32c']);
    printf('MD5 Hash: %s' . PHP_EOL, $info['md5Hash']);
    printf('Content-type: %s' . PHP_EOL, $info['contentType']);
    printf("Temporary hold: " . ($info['temporaryHold'] ? "enabled" : "disabled") . PHP_EOL);
    printf("Event-based hold: " . ($info['eventBasedHold'] ? "enabled" : "disabled") . PHP_EOL);
    if ($info['retentionExpirationTime']) {
        printf("retentionExpirationTime: " . $info['retentionExpirationTime'] . PHP_EOL);
    }
    if (isset($info['metadata'])) {
        printf('Metadata: %s', print_r($info['metadata'], true));
    }
}

Python

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

def blob_metadata(bucket_name, blob_name):
    """Prints out a blob's metadata."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.get_blob(blob_name)

    print('Blob: {}'.format(blob.name))
    print('Bucket: {}'.format(blob.bucket.name))
    print('Storage class: {}'.format(blob.storage_class))
    print('ID: {}'.format(blob.id))
    print('Size: {} bytes'.format(blob.size))
    print('Updated: {}'.format(blob.updated))
    print('Generation: {}'.format(blob.generation))
    print('Metageneration: {}'.format(blob.metageneration))
    print('Etag: {}'.format(blob.etag))
    print('Owner: {}'.format(blob.owner))
    print('Component count: {}'.format(blob.component_count))
    print('Crc32c: {}'.format(blob.crc32c))
    print('md5_hash: {}'.format(blob.md5_hash))
    print('Cache-control: {}'.format(blob.cache_control))
    print('Content-type: {}'.format(blob.content_type))
    print('Content-disposition: {}'.format(blob.content_disposition))
    print('Content-encoding: {}'.format(blob.content_encoding))
    print('Content-language: {}'.format(blob.content_language))
    print('Metadata: {}'.format(blob.metadata))
    print("Temporary hold: ",
          'enabled' if blob.temporary_hold else 'disabled')
    print("Event based hold: ",
          'enabled' if blob.event_based_hold else 'disabled')
    if blob.retention_expiration_time:
        print("retentionExpirationTime: {}"
              .format(blob.retention_expiration_time))

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

puts "Name: #{file.name}"
puts "Bucket: #{bucket.name}"
puts "Storage class: #{bucket.storage_class}"
puts "ID: #{file.id}"
puts "Size: #{file.size} bytes"
puts "Created: #{file.created_at}"
puts "Updated: #{file.updated_at}"
puts "Generation: #{file.generation}"
puts "Metageneration: #{file.metageneration}"
puts "Etag: #{file.etag}"
puts "Owners: #{file.acl.owners.join ','}"
puts "Crc32c: #{file.crc32c}"
puts "md5_hash: #{file.md5}"
puts "Cache-control: #{file.cache_control}"
puts "Content-type: #{file.content_type}"
puts "Content-disposition: #{file.content_disposition}"
puts "Content-encoding: #{file.content_encoding}"
puts "Content-language: #{file.content_language}"
puts "KmsKeyName: #{file.kms_key}"
puts "Event-based hold enabled?: #{file.event_based_hold?}"
puts "Temporary hold enaled?: #{file.temporary_hold?}"
puts "Retention Expiration: #{file.retention_expires_at}"
puts "Metadata:"
file.metadata.each do |key, value|
  puts " - #{key} = #{value}"
end

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用您自己的 OAuth 憑證。
  2. 透過 GET 物件要求使用 cURL 呼叫 JSON API,並將 [VALUES_IN_BRACKETS] 替換成適當的值:
    curl -X GET \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]"

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用您自己的 OAuth 憑證。
  2. 透過 HEAD 物件要求使用 cURL 呼叫 XML API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    curl -I HEAD \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

編輯物件中繼資料

如何編輯和物件相關的中繼資料:

主控台

  1. 在 Google Cloud Platform 主控台中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,找到包含所需物件的值區名稱,然後點選這個名稱,前往該物件的所在位置。

  3. 按一下和物件相關的 [more options] (更多選項) 按鈕 (更多動作圖示。)。

  4. 按一下 [Edit metadata] (編輯中繼資料)。

  5. 在出現的重疊視窗中,對中繼資料進行所需的編輯。

    • 針對標準中繼資料欄位,編輯「Value」(值)。

    • 按一下 [+ Add item] (+ 新增項目) 按鈕,即可新增您的自訂中繼資料。

    • 您可以編輯自訂中繼資料的「Key」(鍵) 和「Value」(值)。

    • 按一下和自訂中繼資料相關聯的 [X],即可刪除自訂中繼資料。

  6. 按一下 [Save] (儲存)。

gsutil

使用 gsutil setmeta -h 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

gsutil setmeta -h "[METADATA_KEY]:[METADATA_VALUE]" gs://[BUCKET_NAME]/[OBJECT_NAME]

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

Operation completed over 1 objects.

請注意,如果要使用 gsutil 新增自訂中繼資料,則必須在中繼資料鍵前面加上 x-goog-meta- 前置字串,以讓 gsutil 識別出這是自訂中繼資料屬性,而不是標準 HTTP 標頭。中繼資料鍵本身不會與 x-goog-meta- 前置字串一起儲存。

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用您自己的 OAuth 憑證。
  2. 建立包含要新增之中繼資料的 .json 檔案。

    針對固定鍵中繼資料 (例如 contentType) 使用以下格式,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    {
      "[STANDARD_METADATA_KEY]": "[STANDARD_METADATA_VALUE]"
    }

    針對自訂中繼資料使用以下格式,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    {
      "metadata": {
        "[CUSTOM_METADATA_KEY]": "[CUSTOM_METADATA_VALUE]"
      }
    }
  3. 透過 PATCH 物件要求使用 cURL 呼叫 JSON API,並將 [VALUES_IN_BRACKETS] 替換成適當的值:
    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        -H "Content-Type: application/json" \
        "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]"

請注意,您也可以透過 UPDATE 物件要求來變更物件的中繼資料。當您使用此方法時,系統會從物件中繼資料中移除要求中未明確指定的任何中繼資料。

XML API

當您使用 XML API 時,只能在寫入物件時設定中繼資料,例如上傳、移動或覆寫物件時。根據上傳物件等操作說明作業時,請一併參考以下指引:

  • -H "[METADATA_NAME]:[METADATA_VALUE]" 新增至您設定的每個中繼資料的要求標頭中。
  • 在任何自訂中繼資料值前面加上 x-goog-meta- 前置字串。

如需更多資訊,請參閱上傳 XML 物件的說明。

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Storage
需要協助嗎?請前往我們的支援網頁