使用版本化物件

總覽 設定

本頁面說明如何列出、存取、還原及刪除非現行物件,這類物件通常適用於已啟用物件版本管理功能的值區。

必要的角色

如要取得管理非目前物件所需的權限,請要求管理員為您授予專案的「儲存空間物件使用者」(roles/storage.objectUser) IAM 角色。這個預先定義的角色包含管理非目前物件所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.objects.create
  • storage.objects.delete
  • storage.objects.get
  • storage.objects.list

您或許還可透過自訂角色取得這些權限。

如要進一步瞭解如何授予專案角色,請參閱「管理專案存取權」。

視用途而定,您可能需要額外權限或其他角色:

  • 如果您打算使用 Google Cloud 主控台執行此頁面上的任務,還需要 storage.buckets.list 權限,但 Storage 物件使用者 (roles/storage.objectUser) 角色並未包含這項權限。如要取得這項權限,請要求管理員為您授予專案的「儲存空間管理員」(roles/storage.admin) 角色。

  • 如果您的值區已停用統一值區層級存取權,則在下列情況下需要額外權限:

    • 如果您打算傳回非最新物件及其 ACL,也需要 storage.objects.getIamPolicy 權限,但該權限並未包含在儲存空間物件使用者 (roles/storage.objectUser) 角色中。如要取得這項權限,請要求管理員為您授予專案的儲存空間物件管理員 (roles/storage.objectAdmin) 角色。

    • 如果您打算重新命名或還原具有 ACL 的非最新物件,還需要 storage.objects.setIamPolicy 權限,但 Storage 物件使用者 (roles/storage.objectUser) 角色並未提供這項權限。如要取得這項權限,請要求管理員為您授予專案的儲存空間物件管理員 (roles/storage.objectAdmin) 角色。

列出非現行物件版本

如要列出使用中和非現行的物件版本,並查看其 generation 編號

控制台

  1. 在 Google Cloud 控制台,前往 Cloud Storage「Buckets」頁面。

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下包含所需物件的值區名稱。

    「Bucket details」頁面隨即開啟,並選取「Objects」分頁標籤。

  3. 如要查看非現行物件,請按一下「顯示」下拉式選單,然後選取「現行和非現行物件」

  4. 在物件清單中,按一下要查看版本的物件名稱。

    「Object details」頁面隨即開啟,並選取「Live Object」分頁。

  5. 按一下「版本記錄」分頁標籤,即可查看物件的所有版本。

指令列

使用 gcloud storage ls --all-versions 指令:

gcloud storage ls --all-versions gs://BUCKET_NAME

其中 BUCKET_NAME 是包含物件的值區名稱。例如:my-bucket

回應類似下列範例:

gs://BUCKET_NAME/OBJECT_NAME1#GENERATION_NUMBER1
gs://BUCKET_NAME/OBJECT_NAME2#GENERATION_NUMBER2
gs://BUCKET_NAME/OBJECT_NAME3#GENERATION_NUMBER3
...

用戶端程式庫

C++

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name) {
  for (auto&& object_metadata :
       client.ListObjects(bucket_name, gcs::Versions{true})) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name()
              << ", generation=" << object_metadata->generation() << "\n";
  }
}

C#

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


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

public class ListFileArchivedGenerationSample
{
	public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFileArchivedGeneration(string bucketName = "your-bucket-name")
	{
		var storage = StorageClient.Create();

		var storageObjects = storage.ListObjects(bucketName, options: new ListObjectsOptions
		{
			Versions = true
		});

		foreach (var storageObject in storageObjects)
		{
			Console.WriteLine($"Filename: {storageObject.Name}, Generation: {storageObject.Generation}");
		}

		return storageObjects;
	}
}

Go

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFilesAllVersion lists both live and noncurrent versions of objects within specified bucket.
func listFilesAllVersion(w io.Writer, bucket string) error {
	// bucket := "bucket-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()

	it := client.Bucket(bucket).Objects(ctx, &storage.Query{
		// Versions true to output all generations of objects
		Versions: true,
	})
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects(): %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name, attrs.Generation, attrs.Metageneration)
	}
	return nil
}

Java

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjectsWithOldVersions {
  public static void listObjectsWithOldVersions(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    Page<Blob> blobs = bucket.list(Storage.BlobListOption.versions(true));

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName() + "," + blob.getGeneration());
    }
  }
}

Node.js

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

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

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

async function listFilesWithOldVersions() {
  const [files] = await storage.bucket(bucketName).getFiles({
    versions: true,
  });

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name, file.generation);
  });
}

listFilesWithOldVersions().catch(console.error);

PHP

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

use Google\Cloud\Storage\StorageClient;

/**
 * List objects in a specified bucket with all archived generations.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_file_archived_generations(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $objects = $bucket->objects([
        'versions' => true,
    ]);

    foreach ($objects as $object) {
        print($object->name() . ',' . $object->info()['generation'] . PHP_EOL);
    }
}

Python

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

from google.cloud import storage


def list_file_archived_generations(bucket_name):
    """Lists all the blobs in the bucket with generation."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    blobs = storage_client.list_blobs(bucket_name, versions=True)

    for blob in blobs:
        print(f"{blob.name},{blob.generation}")

Ruby

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

def list_file_archived_generations bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  bucket.files.each do |file|
    puts "#{file.name},#{file.generation}"
  end
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 Objects: list 要求呼叫 JSON API

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o?versions=true"

    其中 BUCKET_NAME 是包含物件的值區名稱。例如:my-bucket

非現行版本的物件具有 timeDeleted 屬性。

XML API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 GET 值區要求和 versions 查詢字串參數呼叫 XML API

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?versions&list-type=2"

    其中 BUCKET_NAME 是包含物件的值區名稱。例如:my-bucket

與不使用 versions 查詢參數相比,使用這個參數時,GET 要求結果會有一些差異。具體而言,當您在要求中包含 versions 查詢參數時,Cloud Storage 會傳回下列資訊:

  • Version 元素,其中包含每個物件的資訊。
  • DeletedTime 元素,其中包含物件版本變為非現行版本的時間 (已刪除或取代)。
  • `IsLatest 元素,指示特定物件是否為最新版本。
  • 如果值區中有多個物件版本,且只顯示一部分的物件清單時,系統會傳回 NextGenerationMarker 元素。在後續請求的 generationmarker 查詢參數中使用此元素的值,以便從上一個點恢復。generationmarker 查詢參數的使用方式,與您使用 marker 查詢參數瀏覽未版本化值區清單的方式一樣。

存取非現行物件版本

如要在執行下載物件、查看中繼資料或更新中繼資料等工作時,使用非最新版本的物件,請按照下列步驟操作:

控制台

Google Cloud 控制台不提供非最新版本的一般存取權。使用 Google Cloud 主控台時,您只能移動、複製、還原刪除非最新版本。這些動作會透過物件的版本記錄清單執行。

指令列

  1. 將非目前版本的generation 編號附加到物件名稱:

    OBJECT_NAME#GENERATION_NUMBER

    其中:

    • OBJECT_NAME 是舊版的名稱。例如:pets/dog.png
    • GENERATION_NUMBER 是非現行版本的產生號碼。例如:1560468815691234
  2. 使用上一個步驟的字串,按照平常方式處理物件的使用中版本。舉例來說,如要查看非最新物件版本的中繼資料,請使用 gcloud storage objects describe 指令:

    gcloud storage objects describe gs://my-bucket/pets/dog.png#1560468815691234

REST API

JSON API

  1. 將非現行版本的generation 編號附加至物件的 URI:

    https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?generation=GENERATION_NUMBER

    其中:

    • BUCKET_NAME 是包含非最新版本的值區名稱。例如:my-bucket
    • OBJECT_NAME 是舊版的網址編碼名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png
    • GENERATION_NUMBER 是非現行版本的產生號碼。例如:1560468815691234
  2. 使用上一個步驟的 URI,按照平常方式處理物件的使用中版本。舉例來說,如要查看非目前物件版本的結構描述,請使用 cURL 透過 Objects: get 要求呼叫 JSON API

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/my-bucket/o/pets/dog.png?generation=1560468815691234"

XML API

  1. 將非現行版本的generation 編號附加至物件的 URI:

    https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?generation=GENERATION_NUMBER

    其中:

    • BUCKET_NAME 是包含非最新版本的值區名稱。例如:my-bucket
    • OBJECT_NAME 是舊版的網址編碼名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png
    • GENERATION_NUMBER 是非現行版本的世代號碼。例如:1560468815691234
  2. 使用上一個步驟的 URI,按照平常方式處理物件的使用中版本。舉例來說,如要查看非目前物件版本的中繼資料,請使用 cURL 透過 HEAD 物件要求呼叫 XML API

    curl -I GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/my-bucket/pets/dog.png?generation=1560468815691234"

還原非現行物件版本

在 Cloud Storage 中,還原非目前的物件版本,就是製作物件副本。這樣一來,副本就會變成使用中版本,有效還原該版本。如果已存在使用中版本,且值區已啟用物件版本管理功能,則還原非現行版本會導致原有的使用中版本變成非現行版本。

控制台

  1. 在 Google Cloud 控制台,前往 Cloud Storage「Buckets」頁面。

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下包含所需物件的值區名稱。

    「Bucket details」頁面隨即開啟,並選取「Objects」分頁標籤。

  3. 如要查看非現行物件,請按一下「顯示」下拉式選單,然後選取「現行和非現行物件」

  4. 在物件清單中,按一下要還原的物件版本名稱。

    「Object details」頁面隨即開啟,並選取「Live Object」分頁。

  5. 按一下「版本記錄」分頁標籤。

  6. 按一下所需版本的「Restore」按鈕。

    系統會開啟「還原物件版本」窗格。

  7. 按一下「確認」。

指令列

使用 gcloud storage cp 指令:

gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME#GENERATION_NUMBER gs://BUCKET_NAME

其中:

  • BUCKET_NAME 是包含要還原的非最新版本的值區名稱。例如:my-bucket
  • OBJECT_NAME 是您要還原的非目前版本名稱。例如:pets/dog.png
  • GENERATION_NUMBER 是您要還原的非現行版本的世代編號。例如:1560468815691234

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

Operation completed over 1 objects/58.8 KiB.

用戶端程式庫

C++

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
   std::string const& source_object_name,
   std::string const& destination_bucket_name,
   std::string const& destination_object_name,
   std::int64_t source_object_generation) {
  StatusOr<gcs::ObjectMetadata> copy =
      client.CopyObject(source_bucket_name, source_object_name,
                        destination_bucket_name, destination_object_name,
                        gcs::SourceGeneration{source_object_generation});
  if (!copy) throw std::move(copy).status();

  std::cout << "Successfully copied " << source_object_name << " generation "
            << source_object_generation << " in bucket " << source_bucket_name
            << " to bucket " << copy->bucket() << " with name "
            << copy->name()
            << ".\nThe full metadata after the copy is: " << *copy << "\n";
}

C#

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


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

public class CopyFileArchivedGenerationSample
{
    public Google.Apis.Storage.v1.Data.Object CopyFileArchivedGeneration(
        string sourceBucketName = "source-bucket-name",
        string sourceObjectName = "source-file",
        string destBucketName = "destination-bucket-name",
        string destObjectName = "destination-file-name",
        long? generation = 1579287380533984)
    {
        var storage = StorageClient.Create();
        var copyOptions = new CopyObjectOptions
        {
            SourceGeneration = generation
        };

        var copiedFile = storage.CopyObject(sourceBucketName, sourceObjectName,
            destBucketName, destObjectName, copyOptions);

        Console.WriteLine($"Generation {generation} of the object {sourceBucketName}/{sourceObjectName} " +
            $"was copied to to {destBucketName}/{destObjectName}.");

        return copiedFile;
    }
}

Go

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

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

// copyOldVersionOfObject copies a noncurrent version of an object.
func copyOldVersionOfObject(w io.Writer, bucket, srcObject, dstObject string, gen int64) error {
	// bucket := "bucket-name"
	// srcObject := "source-object-name"
	// dstObject := "destination-object-name"

	// gen is the generation of srcObject to copy.
	// gen := 1587012235914578
	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()

	src := client.Bucket(bucket).Object(srcObject)
	dst := client.Bucket(bucket).Object(dstObject)

	// 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 dst object that does not yet exist, set the DoesNotExist precondition.
	dst = dst.If(storage.Conditions{DoesNotExist: true})
	// If the destination object already exists in your bucket, set instead a
	// generation-match precondition using its generation number.
	// attrs, err := dst.Attrs(ctx)
	// if err != nil {
	// 	return fmt.Errorf("object.Attrs: %w", err)
	// }
	// dst = dst.If(storage.Conditions{GenerationMatch: attrs.Generation})

	if _, err := dst.CopierFrom(src.Generation(gen)).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Generation(%v).Run: %w", dstObject, srcObject, gen, err)
	}
	fmt.Fprintf(w, "Generation %v of object %v in bucket %v was copied to %v\n", gen, srcObject, bucket, dstObject)
	return nil
}

Java

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class CopyOldVersionOfObject {
  public static void copyOldVersionOfObject(
      String projectId,
      String bucketName,
      String objectToCopy,
      long generationToCopy,
      String newObjectName) {
    // 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 the GCS object to copy an old version of
    // String objectToCopy = "your-object-name";

    // The generation of objectToCopy to copy
    // long generationToCopy = 1579287380533984;

    // What to name the new object with the old data from objectToCopy
    // String newObjectName = "your-new-object";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request returns a 412 error if the
    // preconditions are not met.
    Storage.BlobTargetOption precondition;
    if (storage.get(bucketName, newObjectName) == null) {
      // For a target object that does not yet exist, set the DoesNotExist precondition.
      // This will cause the request to fail if the object is created before the request runs.
      precondition = Storage.BlobTargetOption.doesNotExist();
    } else {
      // If the destination already exists in your bucket, instead set a generation-match
      // precondition. This will cause the request to fail if the existing object's generation
      // changes before the request runs.
      precondition =
          Storage.BlobTargetOption.generationMatch(
              storage.get(bucketName, newObjectName).getGeneration());
    }

    Storage.CopyRequest copyRequest =
        Storage.CopyRequest.newBuilder()
            .setSource(BlobId.of(bucketName, objectToCopy, generationToCopy))
            .setTarget(BlobId.of(bucketName, newObjectName), precondition)
            .build();
    storage.copy(copyRequest);

    System.out.println(
        "Generation "
            + generationToCopy
            + " of object "
            + objectToCopy
            + " in bucket "
            + bucketName
            + " was copied to "
            + newObjectName);
  }
}

Node.js

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const srcBucketName = "your-unique-bucket-name";

// The ID of the GCS file to copy an old version of
// const srcFilename = "your-file-name";

// The generation of fileToCopy to copy
// const generation = 1579287380533984;

// The ID of the bucket to copy the file to
// const destBucketName = 'target-file-bucket';

// What to name the new file with the old data from srcFilename
// const destFileName = "your-new-file";

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

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

async function copyOldVersionOfFile() {
  // Copies the file to the other bucket

  // 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 copyOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  await storage
    .bucket(srcBucketName)
    .file(srcFilename, {
      generation,
    })
    .copy(storage.bucket(destBucketName).file(destFileName), copyOptions);

  console.log(
    `Generation ${generation} of file ${srcFilename} in bucket ${srcBucketName} was copied to ${destFileName} in bucket ${destBucketName}`
  );
}

copyOldVersionOfFile().catch(console.error);

PHP

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

use Google\Cloud\Storage\StorageClient;

/**
 * Copy archived generation of a given object to a new object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectToCopy The name of the object to copy.
 *        (e.g. 'my-object')
 * @param string $generationToCopy The generation of the object to copy.
 *        (e.g. 1579287380533984)
 * @param string $newObjectName The name of the target object.
 *        (e.g. 'my-object-1579287380533984')
 */
function copy_file_archived_generation(string $bucketName, string $objectToCopy, string $generationToCopy, string $newObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $object = $bucket->object($objectToCopy, [
        'generation' => $generationToCopy,
    ]);

    $object->copy($bucket, [
        'name' => $newObjectName,
    ]);

    printf(
        'Generation %s of object %s in bucket %s was copied to %s',
        $generationToCopy,
        $objectToCopy,
        $bucketName,
        $newObjectName
    );
}

Python

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

from google.cloud import storage


def copy_file_archived_generation(
        bucket_name, blob_name, destination_bucket_name, destination_blob_name, generation
):
    """Copies a blob from one bucket to another with a new name with the same generation."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # destination_bucket_name = "destination-bucket-name"
    # destination_blob_name = "destination-object-name"
    # generation = 1579287380533984

    storage_client = storage.Client()

    source_bucket = storage_client.bucket(bucket_name)
    source_blob = source_bucket.blob(blob_name)
    destination_bucket = storage_client.bucket(destination_bucket_name)

    # 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 if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    destination_generation_match_precondition = 0

    # source_generation selects a specific revision of the source object, as opposed to the latest version.
    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, destination_blob_name, source_generation=generation, if_generation_match=destination_generation_match_precondition
    )

    print(
        "Generation {} of the blob {} in bucket {} copied to blob {} in bucket {}.".format(
            generation,
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
        )
    )

Ruby

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

def copy_file_archived_generation source_bucket_name:,
                                  source_file_name:,
                                  generation:,
                                  destination_bucket_name:,
                                  destination_file_name:
  # The ID of the bucket the original object is in
  # source_bucket_name = "source-bucket-name"

  # The ID of the GCS object to copy
  # source_file_name = "source-file-name"

  # The generation of your GCS object to copy
  # generation = 1579287380533984

  # The ID of the bucket to copy the object to
  # destination_bucket_name = "destination-bucket-name"

  # The ID of the new GCS object
  # destination_file_name = "destination-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  source_bucket = storage.bucket source_bucket_name, skip_lookup: true
  source_file = source_bucket.file source_file_name
  destination_bucket = storage.bucket destination_bucket_name, skip_lookup: true

  destination_file = source_file.copy destination_bucket, destination_file_name, generation: generation

  puts "Generation #{generation} of the file #{source_file.name} in bucket #{source_bucket.name} copied to file " \
       "#{destination_file.name} in bucket #{destination_bucket.name}"
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 POST 物件要求呼叫 JSON API

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Length: 0" \
      "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/OBJECT_NAME?sourceGeneration=GENERATION_NUMBER"

    其中:

    • BUCKET_NAME 是包含要還原的非最新版本的值區名稱。例如:my-bucket
    • OBJECT_NAME 是您要還原的非目前版本的網址編碼名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png
    • GENERATION_NUMBER 是您要還原的非現行版本的世代編號。例如:1560468815691234

XML API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 PUT 物件要求呼叫 XML API

    curl -X PUT \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-copy-source: BUCKET_NAME/OBJECT_NAME" \
      -H "x-goog-copy-source-generation:GENERATION_NUMBER" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    其中:

    • BUCKET_NAME 是包含要還原的非最新版本的值區名稱。例如:my-bucket
    • OBJECT_NAME 是您要還原的非目前版本的網址編碼名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png
    • GENERATION_NUMBER 是您要還原的非現行版本的世代編號。例如:1560468815691234

還原物件版本後,原始的非現行版本仍會保留在值區中。如果您不再需要非現行版本,可以隨後刪除該版本,或是設定物件生命週期管理,在符合您指定條件時移除該版本。

刪除非現行物件版本

控制台

  1. 在 Google Cloud 控制台,前往 Cloud Storage「Buckets」頁面。

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下包含所需物件的值區名稱。

    「Bucket details」頁面隨即開啟,並選取「Objects」分頁標籤。

  3. 如要查看非現行物件,請按一下「顯示」下拉式選單,然後選取「現行和非現行物件」

  4. 前往物件所在位置,該物件可能位於資料夾中。

  5. 在物件清單中,按一下要刪除版本的物件名稱。

    「Object details」(物件詳細資料) 頁面隨即開啟,並選取「Live Object」分頁。

  6. 按一下「版本記錄」分頁標籤。

  7. 勾選所需版本的核取方塊。

  8. 按一下 [Delete] (刪除) 按鈕。

    系統會開啟「刪除版本」窗格。

  9. 在文字欄位中輸入 delete,確認要刪除物件。

  10. 點選「刪除」。

指令列

使用 gcloud storage rm 指令:

gcloud storage rm gs://BUCKET_NAME/OBJECT_NAME#GENERATION_NUMBER

其中:

  • BUCKET_NAME 是包含要刪除的非最新版本的值區名稱。例如:my-bucket
  • OBJECT_NAME 是您要刪除的非目前版本名稱。例如:pets/dog.png
  • GENERATION_NUMBER 是您要刪除的非最新版本的世代號碼。例如:1560468815691234

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

Operation completed over 1 objects.

用戶端程式庫

C++

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::int64_t object_generation) {
  google::cloud::Status status = client.DeleteObject(
      bucket_name, object_name, gcs::Generation{object_generation});
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Deleted " << object_name << " generation "
            << object_generation << " in bucket " << bucket_name << "\n";
}

C#

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


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

public class DeleteFileArchivedGenerationSample
{
    public void DeleteFileArchivedGeneration(
        string bucketName = "your-bucket-name",
        string objectName = "your-object-name",
        long? generation = 1579287380533984)
    {
        var storage = StorageClient.Create();

        storage.DeleteObject(bucketName, objectName, new DeleteObjectOptions
        {
            Generation = generation
        });

        Console.WriteLine($"Generation ${generation} of file {objectName} was deleted from bucket {bucketName}.");
    }
}

Go

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

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

// deleteOldVersionOfObject deletes a noncurrent version of an object.
func deleteOldVersionOfObject(w io.Writer, bucketName, objectName string, gen int64) error {
	// bucketName := "bucket-name"
	// objectName := "object-name"

	// gen is the generation of objectName to delete.
	// gen := 1587012235914578
	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()

	obj := client.Bucket(bucketName).Object(objectName)
	if err := obj.Generation(gen).Delete(ctx); err != nil {
		return fmt.Errorf("Bucket(%q).Object(%q).Generation(%v).Delete: %w", bucketName, objectName, gen, err)
	}
	fmt.Fprintf(w, "Generation %v of object %v was deleted from %v\n", gen, objectName, bucketName)
	return nil
}

Java

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class DeleteOldVersionOfObject {
  public static void deleteOldVersionOfObject(
      String projectId, String bucketName, String objectName, long generationToDelete) {
    // 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";

    // The generation of objectName to delete
    // long generationToDelete = 1579287380533984;

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    storage.delete(BlobId.of(bucketName, objectName, generationToDelete));

    System.out.println(
        "Generation "
            + generationToDelete
            + " of object "
            + objectName
            + " was deleted from "
            + bucketName);
  }
}

Node.js

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

如要驗證 Cloud 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 generation of fileName to delete
// const generation = 1579287380533984;

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

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

async function deleteOldVersionOfFile() {
  // Deletes the file from the bucket with given version
  await storage
    .bucket(bucketName)
    .file(fileName, {
      generation,
    })
    .delete();

  console.log(
    `Generation ${generation} of file ${fileName} was deleted from ${bucketName}`
  );
}

deleteOldVersionOfFile().catch(console.error);

PHP

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an archived generation of the given 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')
 * @param string $generationToDelete the generation of the object to delete.
 *        (e.g. 1579287380533984)
 */
function delete_file_archived_generation(string $bucketName, string $objectName, string $generationToDelete): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $object = $bucket->object($objectName, [
        'generation' => $generationToDelete,
    ]);

    $object->delete();

    printf(
        'Generation %s of object %s was deleted from %s',
        $generationToDelete,
        $objectName,
        $bucketName
    );
}

Python

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

from google.cloud import storage


def delete_file_archived_generation(bucket_name, blob_name, generation):
    """Delete a blob in the bucket with the given generation."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # generation = 1579287380533984

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.delete_blob(blob_name, generation=generation)
    print(
        f"Generation {generation} of blob {blob_name} was deleted from {bucket_name}"
    )

Ruby

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

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

  # The generation of the file to delete
  # generation = 1579287380533984

  require "google/cloud/storage"

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

  file = bucket.file file_name

  file.delete generation: generation

  puts "Generation #{generation} of file #{file_name} was deleted from #{bucket_name}"
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 DELETE 物件要求呼叫 JSON API

    curl -X DELETE \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?generation=GENERATION_NUMBER"

    其中:

    • BUCKET_NAME 是包含要刪除的非最新版本的值區名稱。例如:my-bucket
    • OBJECT_NAME 是您要刪除的非目前版本的網址編碼名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png
    • GENERATION_NUMBER 是您要刪除的非現行版本的世代編號。例如:1560468815691234

XML API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 DELETE 物件要求呼叫 XML API

    curl -X DELETE \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?generation=GENERATION_NUMBER"

    其中:

    • BUCKET_NAME 是包含要刪除的非最新版本的值區名稱。例如:my-bucket
    • OBJECT_NAME 是您要刪除的非目前版本的網址編碼名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png
    • GENERATION_NUMBER 是您要刪除的非現行版本的世代編號。例如:1560468815691234

後續步驟