객체 작성

개요

이 페이지에서는 Cloud Storage 객체를 단일 객체로 작성하는 방법을 설명합니다. 작성 요청은 1~32개의 객체를 취하여 새로운 복합 객체를 만듭니다. 복합 객체는 요청에 지정된 순서 대로 연결된 소스 객체입니다.

객체를 조합할 때 다음에 유의하세요.

  • 소스 객체는 조합 프로세스의 영향을 받지 않습니다. 임시로 사용하려는 경우에는 조합이 성공적으로 완료된 후 이를 삭제해야 합니다.

필수 권한

콘솔

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 compose 명령어를 사용합니다.

gcloud storage objects compose gs://BUCKET_NAME/SOURCE_OBJECT_1 gs://BUCKET_NAME/SOURCE_OBJECT_2 gs://BUCKET_NAME/COMPOSITE_OBJECT_NAME

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 소스 객체를 포함하는 버킷의 이름입니다.
  • SOURCE_OBJECT_1SOURCE_OBJECT_2는 객체 조합에 사용할 소스 객체의 이름입니다.
  • COMPOSITE_OBJECT_NAME은 객체 조합의 결과에 지정할 이름입니다.

클라이언트 라이브러리

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& destination_object_name,
   std::vector<gcs::ComposeSourceObject> const& compose_objects) {
  StatusOr<gcs::ObjectMetadata> composed_object = client.ComposeObject(
      bucket_name, compose_objects, destination_object_name);
  if (!composed_object) throw std::move(composed_object).status();

  std::cout << "Composed new object " << composed_object->name()
            << " in bucket " << composed_object->bucket()
            << "\nFull metadata: " << *composed_object << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ComposeObjectSample
{
    public void ComposeObject(
        string bucketName = "your-bucket-name",
        string firstObjectName = "your-first-object-name",
        string secondObjectName = "your-second-object-name",
        string targetObjectName = "new-composite-object-name")
    {
        var storage = StorageClient.Create();

        var sourceObjects = new List<ComposeRequest.SourceObjectsData>
        {
            new ComposeRequest.SourceObjectsData { Name = firstObjectName },
            new ComposeRequest.SourceObjectsData { Name = secondObjectName }
        };
        //You could add as many sourceObjects as you want here, up to the max of 32.

        storage.Service.Objects.Compose(new ComposeRequest
        {
            SourceObjects = sourceObjects,
            Destination = new Google.Apis.Storage.v1.Data.Object { ContentType = "text/plain" }
        }, bucketName, targetObjectName).Execute();

        Console.WriteLine($"New composite file {targetObjectName} was created in bucket {bucketName}" +
            $" by combining {firstObjectName} and {secondObjectName}.");
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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

// composeFile composes source objects to create a composite object.
func composeFile(w io.Writer, bucket, object1, object2, toObject string) error {
	// bucket := "bucket-name"
	// object1 := "object-name-1"
	// object2 := "object-name-2"
	// toObject := "object-name-3"

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

	src1 := client.Bucket(bucket).Object(object1)
	src2 := client.Bucket(bucket).Object(object2)
	dst := client.Bucket(bucket).Object(toObject)

	// ComposerFrom takes varargs, so you can put as many objects here
	// as you want.
	_, err = dst.ComposerFrom(src1, src2).Run(ctx)
	if err != nil {
		return fmt.Errorf("ComposerFrom: %w", err)
	}
	fmt.Fprintf(w, "New composite object %v was created by combining %v and %v\n", toObject, object1, object2)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ComposeObject {
  public static void composeObject(
      String bucketName,
      String firstObjectName,
      String secondObjectName,
      String targetObjectName,
      String projectId) {
    // 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 first GCS object to compose
    // String firstObjectName = "your-first-object-name";

    // The ID of the second GCS object to compose
    // String secondObjectName = "your-second-object-name";

    // The ID to give the new composite object
    // String targetObjectName = "new-composite-object-name";

    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, targetObjectName) == 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, targetObjectName).getGeneration());
    }

    Storage.ComposeRequest composeRequest =
        Storage.ComposeRequest.newBuilder()
            // addSource takes varargs, so you can put as many objects here as you want, up to the
            // max of 32
            .addSource(firstObjectName, secondObjectName)
            .setTarget(BlobInfo.newBuilder(bucketName, targetObjectName).build())
            .setTargetOptions(precondition)
            .build();

    Blob compositeObject = storage.compose(composeRequest);

    System.out.println(
        "New composite object "
            + compositeObject.getName()
            + " was created by combining "
            + firstObjectName
            + " and "
            + secondObjectName);
  }
}

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 the first GCS file to compose
// const firstFileName = 'your-first-file-name';

// The ID of the second GCS file to compose
// const secondFileName = 'your-second-file-name';

// The ID to give the new composite file
// const destinationFileName = 'new-composite-file-name';

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

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

async function composeFile() {
  const bucket = storage.bucket(bucketName);
  const sources = [firstFileName, secondFileName];

  // Optional:
  // Set a generation-match precondition to avoid potential race conditions
  // and data corruptions. The request to compose 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 combineOptions = {
    ifGenerationMatch: destinationGenerationMatchPrecondition,
  };
  await bucket.combine(sources, destinationFileName, combineOptions);

  console.log(
    `New composite file ${destinationFileName} was created by combining ${firstFileName} and ${secondFileName}`
  );
}

composeFile().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Compose two objects into a single target object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $firstObjectName The name of the first GCS object to compose.
 *        (e.g. 'my-object-1')
 * @param string $secondObjectName The name of the second GCS object to compose.
 *        (e.g. 'my-object-2')
 * @param string $targetObjectName The name of the object to be created.
 *        (e.g. 'composed-my-object-1-my-object-2')
 */
function compose_file(string $bucketName, string $firstObjectName, string $secondObjectName, string $targetObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    // In this example, we are composing only two objects, but Cloud Storage supports
    // composition of up to 32 objects.
    $objectsToCompose = [$firstObjectName, $secondObjectName];

    $targetObject = $bucket->compose($objectsToCompose, $targetObjectName, [
        'destination' => [
            'contentType' => 'application/octet-stream'
        ]
    ]);

    if ($targetObject->exists()) {
        printf(
            'New composite object %s was created by combining %s and %s',
            $targetObject->name(),
            $firstObjectName,
            $secondObjectName
        );
    }
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage


def compose_file(bucket_name, first_blob_name, second_blob_name, destination_blob_name):
    """Concatenate source blobs into destination blob."""
    # bucket_name = "your-bucket-name"
    # first_blob_name = "first-object-name"
    # second_blob_name = "second-blob-name"
    # destination_blob_name = "destination-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    destination = bucket.blob(destination_blob_name)
    destination.content_type = "text/plain"

    # Note sources is a list of Blob instances, up to the max of 32 instances per request
    sources = [bucket.blob(first_blob_name), bucket.blob(second_blob_name)]

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to compose 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.
    # There is also an `if_source_generation_match` parameter, which is not used in this example.
    destination_generation_match_precondition = 0

    destination.compose(sources, if_generation_match=destination_generation_match_precondition)

    print(
        "New composite object {} in the bucket {} was created by combining {} and {}".format(
            destination_blob_name, bucket_name, first_blob_name, second_blob_name
        )
    )
    return destination

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def compose_file bucket_name:, first_file_name:, second_file_name:, destination_file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of the first GCS object to compose
  # first_file_name = "your-first-file-name"

  # The ID of the second GCS object to compose
  # second_file_name = "your-second-file-name"

  # The ID to give the new composite object
  # destination_file_name = "new-composite-file-name"

  require "google/cloud/storage"

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

  destination = bucket.compose [first_file_name, second_file_name], destination_file_name do |f|
    f.content_type = "text/plain"
  end

  puts "Composed new file #{destination.name} in the bucket #{bucket_name} " \
       "by combining #{first_file_name} and #{second_file_name}"
end

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 다음 정보가 포함된 JSON 파일을 만듭니다.

    {
      "sourceObjects": [
        {
          "name": "SOURCE_OBJECT_1"
        },
        {
          "name": "SOURCE_OBJECT_2"
        }
      ],
      "destination": {
        "contentType": "COMPOSITE_OBJECT_CONTENT_TYPE"
      }
    }

    각 항목의 의미는 다음과 같습니다.

    • SOURCE_OBJECT_1SOURCE_OBJECT_2는 객체 조합에 사용할 소스 객체의 이름입니다.
    • COMPOSITE_OBJECT_CONTENT_TYPE은 결과로 생성된 복합 객체의 콘텐츠 유형입니다.
  3. cURL을 사용하여 POST 객체 요청으로 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/COMPOSITE_OBJECT_NAME/compose"

    각 항목의 의미는 다음과 같습니다.

    • JSON_FILE_NAME은 이전 단계에서 만든 파일의 이름입니다.
    • OAUTH2_TOKEN은 가이드에서 이전에 생성한 액세스 토큰입니다.
    • BUCKET_NAME은 소스 객체를 포함하는 버킷의 이름입니다.
    • COMPOSITE_OBJECT_NAME은 객체 조합의 결과에 지정할 이름입니다.

성공한 경우 응답은 결과로 생성된 복합 객체에 대한 객체 리소스입니다.

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 다음 정보가 포함된 XML 파일을 만듭니다.

      <ComposeRequest>
        <Component>
          <Name>SOURCE_OBJECT_1</Name>
        </Component>
        <Component>
          <Name>SOURCE_OBJECT_2</Name>
        </Component>
      </ComposeRequest>

    각 항목의 의미는 다음과 같습니다.

    • SOURCE_OBJECT_1SOURCE_OBJECT_2는 객체 조합에 사용할 소스 객체의 이름입니다.
  3. cURL을 사용하여 PUT 객체 요청과 compose 쿼리 문자열 매개변수로 XML API를 호출합니다.

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: COMPOSITE_OBJECT_CONTENT_TYPE" \
      "https://storage.googleapis.com/BUCKET_NAME/COMPOSITE_OBJECT_NAME?compose"

    각 항목의 의미는 다음과 같습니다.

    • XML_FILE_NAME은 이전 단계에서 만든 파일의 이름입니다.
    • OAUTH2_TOKEN은 가이드에서 이전에 생성한 액세스 토큰입니다.
    • COMPOSITE_OBJECT_CONTENT_TYPE은 결과로 생성된 복합 객체의 콘텐츠 유형입니다.
    • BUCKET_NAME은 소스 객체를 포함하는 버킷의 이름입니다.
    • COMPOSITE_OBJECT_NAME은 객체 조합의 결과에 지정할 이름입니다.

성공하면 빈 응답 본문이 반환됩니다.

다음 단계