Définir les métadonnées d'un objet

Permet de définir les métadonnées d'un objet stocké dans un bucket Cloud Storage.

Pages de documentation incluant cet exemple de code

Pour afficher l'exemple de code utilisé en contexte, consultez la documentation suivante :

Exemple de code

C++

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C++.

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::runtime_error(object_metadata.status().message());
  }

  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::runtime_error(updated.status().message());
  std::cout << "Object updated. The full metadata after the update is: "
            << *updated << "\n";
}

Go

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Go.

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: %v", err)
	}
	defer client.Close()

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

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

Java

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Java.

import com.google.cloud.storage.Blob;
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");
    Blob blob = storage.get(bucketName, objectName);
    // 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();

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

Node.js

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Node.js.

// 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() {
  // Set file metadata.
  const [metadata] = await storage
    .bucket(bucketName)
    .file(fileName)
    .setMetadata({
      // Predefinded metadata for server e.g. 'cacheControl', 'contentDisposition',
      // 'contentEncoding', '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',
      },
    });

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

setFileMetadata().catch(console.error);

Python

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Python.

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)
    metadata = {'color': 'Red', 'name': 'Test'}
    blob.metadata = metadata
    blob.patch()

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

Ruby

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Ruby.

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

Étape suivante

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.