원자적으로 객체 이름 바꾸기

버킷 내에서 객체의 이름을 원자적으로 바꿉니다. 객체 이름을 변경하려면 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 샘플 브라우저 참조하기