设置对象的元数据

设置 Cloud Storage 存储桶中对象的元数据。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& key,
   std::string const& value) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.GetObjectMetadata(bucket_name, object_name);
  if (!object_metadata) throw std::move(object_metadata).status();

  gcs::ObjectMetadata desired = *object_metadata;
  desired.mutable_metadata().emplace(key, value);

  StatusOr<gcs::ObjectMetadata> updated =
      client.UpdateObject(bucket_name, object_name, desired,
                          gcs::Generation(object_metadata->generation()));

  if (!updated) throw std::move(updated).status();
  std::cout << "Object updated. The full metadata after the update is: "
            << *updated << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class SetObjectMetadataSample
{
    public Google.Apis.Storage.v1.Data.Object SetObjectMetadata(
        string bucketName = "your-bucket-name",
        string objectName = "your-object-name",
        string key = "key-to-add",
        string value = "value-to-add")
    {
        var storage = StorageClient.Create();
        var file = storage.GetObject(bucketName, objectName);

        if (file.Metadata == null)
        {
            file.Metadata = new Dictionary<string, string>();
        }
        file.Metadata.Add(key, value);

        file = storage.UpdateObject(file);
        Console.WriteLine($"Updated custom metadata for object {objectName} in bucket {bucketName}");
        return file;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setMetadata sets an object's metadata.
func setMetadata(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	o := client.Bucket(bucket).Object(object)

	// Optional: set a metageneration-match precondition to avoid potential race
	// conditions and data corruptions. The request to update is aborted if the
	// object's metageneration does not match your precondition.
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("object.Attrs: %w", err)
	}
	o = o.If(storage.Conditions{MetagenerationMatch: attrs.Metageneration})

	// Update the object to set the metadata.
	objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
		Metadata: map[string]string{
			"keyToAddOrUpdate": "value",
		},
	}
	if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
		return fmt.Errorf("ObjectHandle(%q).Update: %w", object, err)
	}
	fmt.Fprintf(w, "Updated custom metadata for object %v in bucket %v.\n", object, bucket)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.HashMap;
import java.util.Map;

public class SetObjectMetadata {
  public static void setObjectMetadata(String projectId, String bucketName, String objectName) {
    // 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";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Map<String, String> newMetadata = new HashMap<>();
    newMetadata.put("keyToAddOrUpdate", "value");
    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;
    }

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

    // Does an upsert operation, if the key already exists it's replaced by the new value, otherwise
    // it's added.
    blob.toBuilder().setMetadata(newMetadata).build().update(precondition);

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

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// 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.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

async function setFileMetadata() {
  // Optional: set a meta-generation-match precondition to avoid potential race
  // conditions and data corruptions. The request to set metadata is aborted if the
  // object's metageneration number does not match your precondition.
  const options = {
    ifMetagenerationMatch: metagenerationMatchPrecondition,
  };

  // Set file metadata.
  const [metadata] = await storage
    .bucket(bucketName)
    .file(fileName)
    .setMetadata(
      {
        // Predefined metadata for server e.g. 'cacheControl', 'contentDisposition',
        // 'contentEncoding', 'contentLanguage', 'contentType'
        contentDisposition:
          'attachment; filename*=utf-8\'\'"anotherImage.jpg"',
        contentType: 'image/jpeg',

        // A note or actionable items for user e.g. uniqueId, object description,
        // or other useful information.
        metadata: {
          description: 'file description...',
          modified: '1900-01-01',
        },
      },
      options
    );

  console.log(
    'Updated metadata for object',
    fileName,
    'in bucket ',
    bucketName
  );
  console.log(metadata);
}

setFileMetadata().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Storage\StorageClient;

/**
 * Set a metadata key and value on the specified object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 */
function set_metadata(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update([
        'metadata' => [
            'keyToAddOrUpdate' => 'value',
        ]
    ]);

    printf('Updated custom metadata for object %s in bucket %s', $objectName, $bucketName);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import storage


def set_blob_metadata(bucket_name, blob_name):
    """Set a blob's metadata."""
    # bucket_name = 'your-bucket-name'
    # blob_name = 'your-object-name'

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.get_blob(blob_name)
    metageneration_match_precondition = None

    # Optional: set a metageneration-match precondition to avoid potential race
    # conditions and data corruptions. The request to patch is aborted if the
    # object's metageneration does not match your precondition.
    metageneration_match_precondition = blob.metageneration

    metadata = {'color': 'Red', 'name': 'Test'}
    blob.metadata = metadata
    blob.patch(if_metageneration_match=metageneration_match_precondition)

    print(f"The metadata for the blob {blob.name} is {blob.metadata}")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def set_metadata bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name

  file.update do |file|
    # Fixed key file metadata
    file.content_type = "text/plain"

    # Custom file metadata
    file.metadata["your-metadata-key"] = "your-metadata-value"
  end

  puts "Metadata for #{file_name} has been updated."
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器