组合对象

转到概念

本页面介绍如何组合源对象以创建复合对象。 您可以在单个请求中组合 1 到 32 个源对象。

如需创建复合对象,请按下列说明操作:

控制台

Cloud Console 不支持执行对象组合。 请改为使用 gsutil。

gsutil

使用 gsutil compose 命令:

gsutil 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 参考文档

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::runtime_error(composed_object.status().message());
  }

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

Go

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

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: %v", 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: %v", 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 参考文档

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

    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())
            .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 参考文档

/**
 * 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];

  await bucket.combine(sources, destinationFileName);

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

composeFile().catch(console.error);

Python

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

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"

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

    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 参考文档

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

  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

C#

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

目前,您无法使用 C# 客户端库来编写对象。

PHP

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

如需使用 PHP 编写对象,请参阅 Google\Cloud\Storage\Bucket 参考文档。

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  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 是生成的复合对象的 Content-Type
  3. 使用 cURL,通过 POST Object 请求调用 JSON API

    curl -X POST --data-binary @JSON_FILE_NAME.json \
      -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 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  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 Object 请求和 compose 查询字符串参数调用 XML API

    curl -X PUT --data-binary @XML_FILE_NAME.xml \
      -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 是生成的复合对象的 Content-Type
    • BUCKET_NAME 是包含源对象的存储分区的名称。
    • COMPOSITE_OBJECT_NAME 是您赋予对象组合成果的名称。

如果成功,则返回空的响应正文。

后续步骤