Todos los productos
Search
Centro de documentos

Object Storage Service:Copiar un objeto (Go SDK V1)

Última actualización: Sep 03, 2026

Copie objetos dentro de un bucket o entre buckets de la misma región.

Notas

  • En este tema se usa el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para más información sobre cómo configurarlas, consulte Configure access credentials.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para otras configuraciones, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Debe tener permisos de lectura en el objeto de origen y permisos de lectura y escritura en el bucket de destino.

  • Los buckets de origen y destino no deben tener directivas de retención configuradas. De lo contrario, la copia fallará y se devolverá el error The object you specified is immutable..

  • No se admite la copia entre regiones. Por ejemplo, no puede copiar un objeto de un bucket en China (Hangzhou) a un bucket en China (Qingdao).

Código de ejemplo

Copiar objetos pequeños

Use el método CopyObject para copiar un objeto dentro del mismo bucket o entre distintos buckets de la misma región. Se recomienda usar este método para objetos menores a 1 GB.

Copiar un objeto dentro del mismo bucket

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

Copiar un objeto entre diferentes buckets de la misma región

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

Copiar objetos grandes

El siguiente código de ejemplo copia un objeto grande:

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

Referencias

  • Para ver el código de ejemplo completo sobre cómo copiar objetos, consulte Ejemplo en GitHub.

  • Para consultar la descripción de la operación de API usada para copiar objetos pequeños, véase CopyObject.

  • Para consultar la descripción de la operación de API usada para copiar objetos grandes, véase UploadPartCopy.