Viewing and Editing Object Metadata

This page describes how to view and edit the metadata associated with objects stored in Cloud Storage. For an overview of object metadata, see Object Metadata.

This page does not cover viewing or editing Identity and Access Management (IAM) policies or object Access Control Lists (ACLs), both of which control who is allowed to access your data. See Using IAM Permissions and Creating and Managing ACLs for guides to accomplishing these tasks.

Viewing object metadata

To view the metadata associated with an object:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that contains the desired object, and navigate to the object.

    Certain pieces of object metadata, such as the object's size and storage class, are displayed along with the object's name.

  3. Click the more options button (More actions icon.) associated with the object.

  4. Click Edit metadata.

    The overlay window that appears shows the current values for the object's editable metadata.

gsutil

Use the gsutil ls -L command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

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

If successful, the response looks similar to the following example:

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

If you have sufficient permission, you also see the Access Control List for the object.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation .

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string bucket_name, std::string object_name) {
  gcs::ObjectMetadata meta =
      client.GetObjectMetadata(bucket_name, object_name);
  std::cout << "The metadata is " << meta << std::endl;
}

C#

For more information, see the Cloud Storage C# API reference documentation .

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

For more information, see the Cloud Storage Go API reference documentation .

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

For more information, see the Cloud Storage Java API reference documentation .

// 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("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("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

For more information, see the Cloud Storage Node.js API reference documentation .

// 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

For more information, see the Cloud Storage PHP API reference documentation .

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

For more information, see the Cloud Storage Python API reference documentation .

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

For more information, see the Cloud Storage Ruby API reference documentation .

# 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 APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a GET Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X GET \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]"

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a HEAD Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -I HEAD \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

Editing object metadata

To edit the metadata associated with an object:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that contains the desired object, and navigate to the object.

  3. Click the more options button (More actions icon.) associated with the object.

  4. Click Edit metadata.

  5. In the overlay window that appears, make the desired edits to the metadata.

    • For standard metadata fields, edit the Value.

    • Add your own custom metadata by clicking the + Add item button.

    • You can edit both the Key and Value of your custom metadata.

    • Delete your custom metadata by clicking the associated X.

  6. Click Save.

gsutil

Use the gsutil setmeta -h command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

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

If successful, the response looks like the following example:

Operation completed over 1 objects.

Note that if you are adding custom metadata with gsutil, you must prefix your metadata key with x-goog-meta- for gsutil to recognize that this is a custom metadata attribute, rather than a standard HTTP header. The metadata key itself is not stored with the x-goog-meta- prefix.

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the metadata you wish to add.

    For fixed-key metadata such as contentType, use the following format, replacing [VALUES_IN_BRACKETS] with appropriate values:

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

    For custom metadata, use the following format, replacing [VALUES_IN_BRACKETS] with appropriate values:

    {
      "metadata": {
        "[CUSTOM_METADATA_KEY]": "[CUSTOM_METADATA_VALUE]"
      }
    }
  3. Use cURL to call the JSON API with a PATCH Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    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]"

Note that you can also change an object's metadata with an UPDATE Object request. When using this method, any metadata that is not explicitly specified in the request is removed from the object's metadata.

XML API

When working with the XML API, metadata can only be set at the time the object is written, such as when uploading, moving, or overwriting the object. Follow instructions such as uploading an object with the following guidelines:

  • Add -H "[METADATA_NAME]:[METADATA_VALUE]" to the request header for each metadata value you are setting.
  • Prefix x-goog-meta- to any custom metadata values.

For more information, see Upload an Object for XML.

¿Te sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

¿Necesitas ayuda? Visita nuestra página de asistencia.