Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Copy an object (Go SDK V1)

Son Güncelleme:Oct 01, 2026

Bir paket içindeki veya aynı bölgedeki farklı paketler arasındaki nesneleri kopyalayın.

Notlar

  • Bu konuda Çin (Hangzhou) bölgesinin genel uç noktası kullanılmıştır. OSS ile aynı bölgede bulunan diğer Alibaba Cloud hizmetlerinden OSS'ye erişmek için dahili uç nokta kullanın. OSS bölgeleri ve uç noktaları hakkında daha fazla bilgi için bkz. Bölgeler ve uç noktalar.

  • Bu konuda erişim kimlik bilgileri ortam değişkenlerinden alınır. Erişim kimlik bilgilerinin nasıl yapılandırılacağı hakkında daha fazla bilgi için bkz. Erişim kimlik bilgilerini yapılandırma.

  • Bu konu, bir OSS uç noktası kullanarak bir OSSClient örneği oluşturmayı göstermektedir. Özel etki alanı kullanma veya Security Token Service (STS) kimlik bilgileriyle kimlik doğrulama gibi alternatif yapılandırmalar için bkz. İstemci yapılandırma (Go SDK V1).

  • Kaynak nesne üzerinde okuma izniniz ve hedef paket üzerinde okuma/yazma izniniz olmalıdır.

  • Kaynak ve hedef paketlerde bekletme ilkeleri yapılandırılmamış olmalıdır. Aksi takdirde kopyalama işlemi başarısız olur ve The object you specified is immutable. hatası döndürülür.

  • Bölgeler arası kopyalama desteklenmez. Örneğin, Çin (Hangzhou) bölgesindeki bir paketten Çin (Qingdao) bölgesindeki bir pakete nesne kopyalayamazsınız.

Örnek kod

Küçük nesneleri kopyalama

Aynı paket içinde veya aynı bölgedeki farklı paketler arasında bir nesneyi kopyalamak için CopyObject yöntemini kullanın. Bu yöntemi 1 GB'den küçük nesneler için kullanmanızı öneririz.

Aynı paket içindeki bir nesneyi kopyalama

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name, for example, examplebucket.
	bucketName := "examplebucket"
	// Specify the full path of the source object, for example, srcdir/srcobject.jpg.
	objectName := "srcdir/srcobject.jpg"
	// Specify the full path of the destination object, for example, destdir/destobject.jpg.
	destObjectName := "destdir/destobject.jpg"

	// Get the bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify the metadata of the destination object.
	expires := time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
	tag1 := oss.Tag{
		Key:   "a",
		Value: "1",
	}

	taggingInfo := oss.Tagging{
		Tags: []oss.Tag{tag1},
	}

	options := []oss.Option{
		oss.MetadataDirective(oss.MetaReplace),
		oss.Expires(expires),
		oss.SetTagging(taggingInfo),
		// Copy the object tagging of the source object to the destination object.
		// oss.TaggingDirective(oss.TaggingCopy),
		// Specify the access permissions (ACL) of the destination object as private when the destination object is created.
		// oss.ObjectACL(oss.ACLPrivate),
		// Specify the customer master key (CMK) managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
		// oss.ServerSideEncryptionKeyID("9468da86-3509-4f8d-a61e-6eab1eac****"),
		// Specify the server-side encryption algorithm that OSS uses to create the destination object.
		// oss.ServerSideEncryption("AES256"),
		// Copy the metadata of the source object to the destination object.
		// oss.MetadataDirective(oss.MetaCopy),
		// Specify whether the CopyObject operation overwrites a destination object that has the same name. In this example, the value is set to true, which prevents overwriting an object that has the same name.
		// oss.ForbidOverWrite(true),
		// If the ETag of the source object matches the ETag you provide, the copy operation is performed and 200 OK is returned.
		// oss.CopySourceIfMatch("5B3C1A2E053D763E1B002CC607C5****"),
		// If the ETag of the source object does not match the ETag you provide, the copy operation is performed and 200 OK is returned.
		// oss.CopySourceIfNoneMatch("5B3C1A2E053D763E1B002CC607C5****"),
		// If the specified time is earlier than the actual modification time of the object, the object is copied and 200 OK is returned.
		// oss.CopySourceIfModifiedSince(time.Date(2021, time.December, 9, 7, 1, 56, 0, time.UTC)),
		// If the specified time is the same as or later than the actual modification time of the object, the object is copied and 200 OK is returned.
		// oss.CopySourceIfUnmodifiedSince(time.Date(2021, time.December, 9, 7, 1, 56, 0, time.UTC)),
		// Specify the storage class of the object. In this example, the value is set to Standard, which specifies the Standard storage class.
		// oss.StorageClass("Standard"),
	}

	// Use the specified metadata to overwrite the metadata of the source object.
	_, err = bucket.CopyObject(objectName, destObjectName, options...)
	if err != nil {
		log.Fatalf("Failed to copy object from '%s' to '%s': %v", objectName, destObjectName, err)
	}

	log.Printf("Successfully copied object from '%s' to '%s'", objectName, destObjectName)
}

Aynı bölgedeki farklı paketler arasında bir nesneyi kopyalama

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the source bucket name, for example, srcbucket.
	srcBucketName := "srcbucket"
	// Specify the full path of the source object, for example, srcobject.jpg.
	srcObjectName := "srcobject.jpg"
	// Specify the full path of the destination object, for example, destobject.jpg.
	dstObjectName := "destobject.jpg"
	// Specify the destination bucket name, for example, destbucket.
	destBucketName := "destbucket"

	// Get the destination bucket instance.
	bucket, err := client.Bucket(destBucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", destBucketName, err)
	}

	// Copy the srcobject.jpg object from the srcbucket bucket to the destobject.jpg object in the destbucket bucket.
	_, err = bucket.CopyObjectFrom(srcBucketName, srcObjectName, dstObjectName)
	if err != nil {
		log.Fatalf("Failed to copy object from '%s/%s' to '%s/%s': %v", srcBucketName, srcObjectName, destBucketName, dstObjectName, err)
	}

	log.Printf("Successfully copied object from '%s/%s' to '%s/%s'", srcBucketName, srcObjectName, destBucketName, dstObjectName)
}

Büyük nesneleri kopyalama

Aşağıdaki örnek kod büyük bir nesneyi kopyalar:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name, for example, examplebucket.
	bucketName := "examplebucket"

	// Get the bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify the full path of the source object, for example, srcobject.txt.
	objectSrc := "srcobject.txt"
	// Specify the full path of the destination object, for example, destobject.txt.
	objectDest := "destobject.txt"
	// Specify the full path of the local file.
	fileName := "D:\\localpath\\examplefile.txt"

	// Split the file into multiple parts.
	chunks, err := oss.SplitFileByPartNum(fileName, 3)
	if err != nil {
		log.Fatalf("Failed to split file: %v", err)
	}

	// Upload the file to OSS.
	err = bucket.PutObjectFromFile(objectSrc, fileName)
	if err != nil {
		log.Fatalf("Failed to upload object '%s' from file '%s': %v", objectSrc, fileName, err)
	}

	// Initialize the multipart upload.
	imur, err := bucket.InitiateMultipartUpload(objectDest)
	if err != nil {
		log.Fatalf("Failed to initiate multipart upload for '%s': %v", objectDest, err)
	}

	var parts []oss.UploadPart
	for _, chunk := range chunks {
		// Set multipart upload options.
		options := []oss.Option{}

		// Perform the multipart copy.
		part, err := bucket.UploadPartCopy(imur, bucketName, objectSrc, chunk.Offset, chunk.Size, chunk.Number, options...)
		if err != nil {
			log.Fatalf("Failed to upload part %d of '%s': %v", chunk.Number, objectSrc, err)
		}
		parts = append(parts, part)
	}

	// Complete the multipart upload.
	cmur, err := bucket.CompleteMultipartUpload(imur, parts)
	if err != nil {
		log.Fatalf("Failed to complete multipart upload for '%s': %v", objectDest, err)
	}

	log.Printf("Multipart upload completed successfully for '%s'. cmur: %v", objectDest, cmur)
}

İlgili konular

  • Nesneleri kopyalamaya ilişkin tam örnek kod için bkz. GitHub örneği.

  • Küçük nesneleri kopyalamak için kullanılan API işleminin açıklaması için bkz. CopyObject.

  • Büyük nesneleri kopyalamak için kullanılan API işleminin açıklaması için bkz. UploadPartCopy.