更改对象存储类别

本页面介绍了如何通过重写对象来更改存储桶中对象的存储类别

  • 如需了解如何在不重写对象的情况下更改对象存储类别,请参阅对象生命周期管理功能。
  • 如需了解 Cloud Storage 如何自动管理对象的存储类别,请参阅自动类功能

所需权限

控制台

无法通过 Google Cloud 控制台设置各个对象存储类别。请改用 Google Cloud CLI。

命令行

为使用命令行实用程序完成本指南,您必须拥有适当的 IAM 权限。如果您要访问的对象在不是由您创建的项目中,则可能需要项目所有者为您提供包含必要权限的角色。

如需查看特定操作所需权限的列表,请参阅 gcloud storage 命令的 IAM 权限

如需查看相关角色的列表,请参阅 Cloud Storage 角色。或者,您也可以创建一个自定义角色,并为其提供具体受限的权限。

客户端库

如需使用 Cloud Storage 客户端库完成本指南,您必须拥有适当的 IAM 权限。如果您要访问的对象在不是由您创建的项目中,则可能需要项目所有者为您提供包含必要权限的角色。

除非另有说明,否则客户端库请求通过 JSON API 发出,并且需要 JSON 方法的 IAM 权限中列出的权限。如需查看使用客户端库发出请求时调用了哪些 JSON API 方法,请记录原始请求

如需查看相关 IAM 角色的列表,请参阅 Cloud Storage 角色。或者,您也可以创建一个自定义角色,并为其提供具体受限的权限。

REST API

JSON API

如需使用 JSON API 完成本指南,您必须拥有适当的 IAM 权限。如果您要访问的对象在不是由您创建的项目中,则可能需要项目所有者为您提供包含必要权限的角色。

如需查看特定操作所需的权限列表,请参阅 JSON 方法的 IAM 权限

如需查看相关角色的列表,请参阅 Cloud Storage 角色。或者,您也可以创建一个自定义角色,并为其提供具体受限的权限。

更改对象的存储类别

如需更改对象的存储类别,请完成以下步骤:

控制台

无法通过 Google Cloud 控制台设置各个对象存储类别。请改用 Google Cloud CLI。

命令行

gcloud storage objects update 命令与 --storage-class 标志结合使用。例如:

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --storage-class=STORAGE_CLASS

其中:

  • BUCKET_NAME 是包含您要更改其类别的对象的存储桶的名称。例如 my-bucket
  • OBJECT_NAME 是您想要更改其类别的对象的名称,例如 pets/dog.png
  • STORAGE_CLASS 是对象的新存储类别,例如 nearline

客户端库

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& storage_class) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.RewriteObjectBlocking(
          bucket_name, object_name, bucket_name, object_name,
          gcs::WithObjectMetadata(
              gcs::ObjectMetadata().set_storage_class(storage_class)));
  if (!object_metadata) throw std::move(object_metadata).status();

  std::cout << "Changed storage class of object " << object_metadata->name()
            << " in bucket " << object_metadata->bucket() << " to "
            << object_metadata->storage_class() << "\n";
}

C#

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

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


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

public class ChangeFileStorageClassSample
{
    public Google.Apis.Storage.v1.Data.Object ChangeFileStorageClass(
        string bucketName = "your-bucket-name",
        string objectName = "your-object-name",
        string storageClass = StorageClasses.Standard)
    {
        var storage = StorageClient.Create();

        // Changing storage class requires a rewrite operation, which can only be done
        // by the underlying service
        var obj = new Google.Apis.Storage.v1.Data.Object { StorageClass = storageClass };
        storage.Service.Objects.Rewrite(obj, bucketName, objectName, bucketName, objectName).Execute();

        var file = storage.GetObject(bucketName, objectName);
        Console.WriteLine($"Object {objectName} in bucket {bucketName} had" +
            $" its storage class set to {storageClass}.");

        return file;
    }
}

Go

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

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

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

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

// changeObjectStorageClass changes the storage class of a single object.
func changeObjectStorageClass(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 generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to copy is aborted if the
	// object's generation number 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{GenerationMatch: attrs.Generation})

	// See the StorageClass documentation for other valid storage classes:
	// https://cloud.google.com/storage/docs/storage-classes
	newStorageClass := "COLDLINE"
	// You can't change an object's storage class directly, the only way is
	// to rewrite the object with the desired storage class.
	copier := o.CopierFrom(o)
	copier.StorageClass = newStorageClass
	if _, err := copier.Run(ctx); err != nil {
		return fmt.Errorf("copier.Run: %w", err)
	}
	fmt.Fprintf(w, "Object %v in bucket %v had its storage class set to %v\n", object, bucket, newStorageClass)
	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.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;

public class ChangeObjectStorageClass {
  public static void changeObjectStorageClass(
      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();
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob sourceBlob = storage.get(blobId);
    if (sourceBlob == null) {
      System.out.println("The object " + objectName + " wasn't found in " + bucketName);
      return;
    }

    // See the StorageClass documentation for other valid storage classes:
    // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
    StorageClass storageClass = StorageClass.COLDLINE;

    // You can't change an object's storage class directly, the only way is to rewrite the object
    // with the desired storage class

    BlobInfo targetBlob = BlobInfo.newBuilder(blobId).setStorageClass(storageClass).build();

    // 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.BlobSourceOption precondition =
        Storage.BlobSourceOption.generationMatch(sourceBlob.getGeneration());

    Storage.CopyRequest request =
        Storage.CopyRequest.newBuilder()
            .setSource(blobId)
            .setSourceOptions(precondition) // delete this line to run without preconditions
            .setTarget(targetBlob)
            .build();
    Blob updatedBlob = storage.copy(request).getResult();

    System.out.println(
        "Object "
            + objectName
            + " in bucket "
            + bucketName
            + " had its storage class set to "
            + updatedBlob.getStorageClass().name());
  }
}

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

// The name of a storage class
// See the StorageClass documentation for other valid storage classes:
// https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
// const storageClass = 'coldline';

async function fileChangeStorageClass() {
  // Optional:
  // Set a generation-match precondition to avoid potential race conditions
  // and data corruptions. The request to copy is aborted if the object's
  // generation number does not match your precondition. For a destination
  // object that does not yet exist, set the ifGenerationMatch precondition to 0
  // If the destination object already exists in your bucket, set instead a
  // generation-match precondition using its generation number.
  const setStorageClassOptions = {
    ifGenerationMatch: generationMatchPrecondition,
  };

  await storage
    .bucket(bucketName)
    .file(fileName)
    .setStorageClass(storageClass, setStorageClassOptions);

  console.log(`${fileName} has been set to ${storageClass}`);
}

fileChangeStorageClass().catch(console.error);

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Change the storage class of the given file.
 *
 * @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')
 * @param string $storageClass The storage class of the new object.
 *        (e.g. 'COLDLINE')
 */
function change_file_storage_class(string $bucketName, string $objectName, string $storageClass): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);

    // Storage class cannot be changed directly. But we can rewrite the object
    // using the new storage class.

    $newObject = $object->rewrite($bucket, [
        'storageClass' => $storageClass,
    ]);

    printf(
        'Object %s in bucket %s had its storage class set to %s',
        $objectName,
        $bucketName,
        $newObject->info()['storageClass']
    );
}

Python

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

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

from google.cloud import storage

def change_file_storage_class(bucket_name, blob_name):
    """Change the default storage class of the blob"""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    generation_match_precondition = None

    # Optional: set a generation-match precondition to avoid potential race
    # conditions and data corruptions. The request is aborted if the
    # object's generation number does not match your precondition.
    blob.reload()  # Fetch blob metadata to use in generation_match_precondition.
    generation_match_precondition = blob.generation

    blob.update_storage_class("NEARLINE", if_generation_match=generation_match_precondition)

    print(
        "Blob {} in bucket {} had its storage class set to {}".format(
            blob_name,
            bucket_name,
            blob.storage_class
        )
    )
    return blob

Ruby

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

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

def change_file_storage_class 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.storage_class = "NEARLINE"

  puts "File #{file_name} in bucket #{bucket_name} had its storage class set to #{file.storage_class}"
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。如需了解相关说明,请参阅 API 身份验证
  2. 创建一个包含以下信息的 JSON 文件:

    {
      "storageClass": "STORAGE_CLASS"
    }

    其中:

    • STORAGE_CLASS 是对象的新存储类别,例如 nearline
  3. 使用 cURL,通过 POST Object 请求调用 JSON API

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/OBJECT_NAME"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的 JSON 文件的路径。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是包含原始对象的存储桶的名称。例如 my-bucket
    • OBJECT_NAME 是对象的网址编码名称。例如,pets/dog.png 的网址编码为 pets%2Fdog.png

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。如需了解相关说明,请参阅 API 身份验证
  2. 使用 cURL,通过 PUT Object 请求调用 XML API

    curl -X PUT --data-binary @OBJECT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: OBJECT_CONTENT_TYPE" \
      -H "x-goog-storage-class: STORAGE_CLASS" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    其中:

    • OBJECT 是您想要更改其存储类别的对象的本地路径(使用 XML API 更改存储类别时,您必须重新上传对象),例如 Desktop/dog.png
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • OBJECT_CONTENT_TYPE 是该对象的内容类型,例如 image/png
    • STORAGE_CLASS 是对象的新存储类别,例如 nearline
    • BUCKET_NAME 是包含要重写的对象的存储桶的名称,例如 my-bucket
    • OBJECT_NAME 是要重写的对象的网址编码名称。例如,pets/dog.png 的网址编码为 pets%2Fdog.png

后续步骤