以原子方式重新命名物件

在值區中以原子方式重新命名物件。如要重新命名物件,可以使用 Objects: move 方法。

程式碼範例

C#

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

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


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

public class MoveObjectSample
{
    /// <summary>
    /// Moves an object within a bucket with hierarchical namespace enabled.
    /// </summary>
    /// <param name="sourceBucketName">Name of the source bucket containing the object to move.</param>
    /// <param name="sourceObjectName">The name of the source object to move within the bucket.</param>
    /// <param name="destinationObjectName">The name of the new object to move to within the bucket.</param>
    public void MoveObject(
        string sourceBucketName = "source-bucket-name",
        string sourceObjectName = "source-object-name",
        string destinationObjectName = "destination-object-name")
    {
        var storage = StorageClient.Create();
        storage.MoveObject(sourceBucketName, sourceObjectName, destinationObjectName);
        Console.WriteLine($"Moved {sourceBucketName}/{sourceObjectName} to " + $"{sourceBucketName}/{destinationObjectName} within a hierarchical namespace enabled bucket.");
    }
}

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

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

// The new ID for your GCS file
// const destFileName = 'your-new-file-name';

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

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

async function moveFileAtomic() {
  // 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 moveOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  // Moves the file automatically within the HNS enabled bucket
  await storage
    .bucket(bucketName)
    .file(srcFileName)
    .moveFileAtomic(destFileName, moveOptions);

  console.log(
    `gs://${bucketName}/${srcFileName} moved to gs://${bucketName}/${destFileName}`
  );
}

moveFileAtomic().catch(console.error);

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Move an object to a new name within HNS-enabled bucket.
 *
 * @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 $newObjectName the destination object name.
 *        (e.g. 'my-other-object')
 */
function move_object_atomic(string $bucketName, string $objectName, string $newObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->move($newObjectName);
    printf('Moved gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName,
        $objectName,
        $bucketName,
        $newObjectName);
}

Python

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

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

from google.cloud import storage


def move_object(bucket_name: str, blob_name: str, new_blob_name: str) -> None:
    """Moves a blob to a new name within the same bucket using the move API."""
    # The name of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The name of your GCS object to move
    # blob_name = "your-file-name"

    # The new name of the GCS object
    # new_blob_name = "new-file-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob_to_move = bucket.blob(blob_name)

    # Use move_blob to perform an efficient, server-side move.
    moved_blob = bucket.move_blob(
        blob=blob_to_move, new_name=new_blob_name
    )

    print(f"Blob {blob_to_move.name} has been moved to {moved_blob.name}.")

Ruby

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

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

def move_object bucket_name:, source_file_name:, destination_file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of your GCS object
  # source_file_name = "your-file-name"

  # The new object name which you want to craete
  # destination_file_name = "your-new-file-name"

  require "google/cloud/storage"

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

  bucket.move_file source_file_name, destination_file_name
  fetch_file = bucket.file destination_file_name
  puts "New File #{fetch_file.name} created\n"
end

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器