All Products
Search
Document Center

Object Storage Service:Copy objects

Last Updated:Aug 11, 2025

You can copy an object from a source bucket to a destination bucket within the same region without modifying the object's content. This operation is often used for data backup and migration.

Limits

Objects cannot be copied between buckets located in different regions. For example, you cannot copy objects from buckets in the China (Hangzhou) region to buckets in the China (Shanghai) region.

Usage notes

  • If you copy a large number of objects and immediately set their storage class to Deep Cold Archive, you may incur high PUT request fees. To reduce costs, configure lifecycle rules to transition these objects to Deep Cold Archive objects after they are copied.

  • You must have read permissions on the source object and read and write permissions on the destination bucket. Otherwise, the copy operation fails.

  • Make sure that no retention policies are configured for the source bucket and the destination bucket. Otherwise, the following error message is returned: The object you specified is immutable.

  • By default, when you copy an object that has the same name as an existing object in the destination bucket, the copied object overwrites the existing object in the destination bucket. You can use one of the following methods to protect your objects from being unexpectedly overwritten:

    • Enable versioning for the destination bucket

      If versioning is enabled for the destination bucket, deleted and overwritten objects in the destination bucket are saved as previous versions. You can recover a previous version at any time. For more information, see Versioning.

    • Include the x-oss-forbid-overwrite header in the copy request

      You can include the x-oss-forbid-overwrite header in the copy request and set the header to true to disable object overwriting. If you copy an object that has the same name as an existing object in the destination bucket, the object fails to be copied and the FileAlreadyExists error code is returned.

Methods

Use ossbrowser

If you use ossbrowser to copy an object, the object must be less than 5 GB in size. For more information about how to use ossbrowser to copy an object, see Common operations.

Use OSS SDKs

The following code provides examples on how to call the CopyObject operation to copy an object less than 1 GB in size by using OSS SDKs for common programming languages. For more information about how to copy an object less than 1 GB in size by using OSS SDKs for other programming languages, and how to call the UploadPartCopy operation to copy an object greater than 1 GB in size, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the source bucket. 
        String sourceBucketName = "srcexamplebucket";
        // Specify the full path of the source object. Do not include the bucket name in the full path. 
        String sourceKey = "srcexampleobject.txt";
        // Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. 
        String destinationBucketName = "desexamplebucket";
        // Specify the full path of the destination object. Do not include the bucket name in the full path. 
        String destinationKey = "desexampleobject.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create a CopyObjectRequest object. 
            CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceKey, destinationBucketName, destinationKey);

            // Configure new metadata for the object. 
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("text/plain");
            // Specify whether the CopyObject operation overwrites an object that has the same name. In this example, this parameter is set to true, which specifies that the operation does not overwrite an object that has the same name. 
            // meta.setHeader("x-oss-forbid-overwrite", "true");
            // Specify the path of the source object. 
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE, "/examplebucket/recode-test.txt");
            // If the ETag value of the source object is the same as the ETag value specified in the request, OSS copies the object and returns 200 OK. 
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_MATCH, "5B3C1A2E053D763E1B002CC607C5****");
            // If the ETag value of the source object is different from the ETag value specified in the request, OSS copies the object and returns 200 OK. 
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_NONE_MATCH, "5B3C1A2E053D763E1B002CC607C5****");
            // If the time that is specified in the request is later than or the same as the time when the object is modified, OSS copies the object and returns 200 OK. 
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_UNMODIFIED_SINCE, "2021-12-09T07:01:56.000Z");
            // If the source object is modified after the time specified in the request, OSS copies the object. 
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_MODIFIED_SINCE, "2021-12-09T07:01:56.000Z");
            // Specify the method that is used to configure the metadata of the destination object. In this example, the method is set to COPY, which specifies that the metadata of the source object is copied to the destination object. 
            // meta.setHeader(OSSHeaders.COPY_OBJECT_METADATA_DIRECTIVE, "COPY");
            // Specify the server-side encryption algorithm that is used to encrypt the destination object when the object is created. 
            // meta.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
            // Specify the customer master key (CMK) that is managed by Key Management Service (KMS). This parameter takes effect only when you set x-oss-server-side-encryption to KMS. 
            // meta.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION_KEY_ID, "9468da86-3509-4f8d-a61e-6eab1eac****");
            // Specify the access control list (ACL) of the destination object. In this example, the ACL is set to private, which specifies that only the object owner and authorized users have read and write permissions on the object. 
            // meta.setHeader(OSSHeaders.OSS_OBJECT_ACL, CannedAccessControlList.Private);
            // Specify the storage class of the destination object. In this example, the storage class is set to Standard. 
            // meta.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard);
            // Specify tags for the destination object. You can specify multiple tags for the object at a time. 
            // meta.setHeader(OSSHeaders.OSS_TAGGING, "a:1");
            // Specify the method that is used to configure tags for the destination object. In this example, the method is set to COPY, which specifies that the tags of the source object are copied to the destination object. 
            // meta.setHeader(OSSHeaders.COPY_OBJECT_TAGGING_DIRECTIVE, "COPY");
            copyObjectRequest.setNewObjectMetadata(meta);

            // Copy the source object. 
            CopyObjectResult result = ossClient.copyObject(copyObjectRequest);
            System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                 
const OSS = require('ali-oss');
const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. Example: examplebucket. 
  bucket: 'examplebucket',
  // Specify whether to enable HTTPS. If you set secure to true, HTTPS is enabled. 
  // secure: true
})

// Copy an object within a bucket. 
async function copySmallObjecInSameBucket() {
  try {
    // Specify the full paths of the source object and the destination object. Do not include the bucket name in the full paths. 
    // Specify HTTP headers and metadata for the destination object. 
    const result = await client.copy('destexampleobject.txt', 'srcexampleobject.txt', {
      // Configure the headers parameter to specify HTTP headers for the destination object. If you do not configure the headers parameter, the HTTP headers of the destination object are the same as the HTTP headers of the source object. The HTTP headers of the source object are copied. 
      headers: {
        'Cache-Control': 'no-cache',
        // If the ETag value of the source object is the same as the ETag value specified in the request, OSS copies the object and returns 200 OK. 
        'if-match': '5B3C1A2E053D763E1B002CC607C5****',
        // If the ETag value that you specify in the request is different from the ETag value of the source object, OSS copies the object and returns 200 OK. 
        'if-none-match': '5B3C1A2E053D763E1B002CC607C5****',
        // If the time that is specified in the request is earlier than the time when the object is modified, OSS copies the object and returns 200 OK. 
        'if-modified-since': '2021-12-09T07:01:56.000Z',
        // If the source object has not been modified since the specified time, the object is copied and 200 OK is returned. 
        'if-unmodified-since': '2021-12-09T07:01:56.000Z',
        // Specify the access control list (ACL) of the destination object. In this example, the ACL is set to private, which indicates that only the object owner and authorized users have read and write permissions on the object. 
        'x-oss-object-acl': 'private',
        // Specify tags for the object. You can specify multiple tags for the object at the same time. 
        'x-oss-tagging': 'Tag1=1&Tag2=2',
        // Specify whether the CopyObject operation overwrites an existing object that has the same name. In this example, this parameter is set to true, which specifies that the CopyObject operation does not overwrite an existing object that has the same name. 
        'x-oss-forbid-overwrite': 'true',
      },
      // Configure the meta parameter to specify the metadata of the destination object. If you do not configure the meta parameter, the metadata of the destination object is the same as the metadata of the source object. The metadata of the source object is copied. 
      meta: {
        location: 'hangzhou',
        year: 2015,
        people: 'mary',
      },
    });
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

copySmallObjecInSameBucket()
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the source bucket. Example: srcexamplebucket. 
var sourceBucket = "srcexamplebucket";
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. 
var sourceObject = "srcdir/scrobject.txt";
// Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket. Example: destbucket. 
var targetBucket = "destbucket";
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. 
var targetObject = "destdir/destobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    var metadata = new ObjectMetadata();
    // Specify user metadata. The user metadata is stored as key-value pairs. For example, the key is mk1 and the value is mv1. 
    metadata.AddHeader("mk1", "mv1");
    metadata.AddHeader("mk2", "mv2");
    var req = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject)
    {
        // If the value of NewObjectMetadata is null, the COPY mode is used and the metadata of the source object is copied to the destination object. If the value of NewObjectMetadata is not null, the REPLACE mode is used and the metadata of the destination object is overwritten by the metadata specified in the request. 
        NewObjectMetadata = metadata 
    };
    // Copy the object. 
    client.CopyObject(req);
    Console.WriteLine("Copy object succeeded");
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2} \tHostID: {3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
// Specify the name of the source bucket. 
String srcBucketName = "srcbucket";
// Specify the full path of the source object. 
String srcObjectKey = "dir1/srcobject.txt";
// Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. 
String destBucketName = "destbucket";
// Specify the full path of the destination object. 
String destObjectKey = "dir2/destobject.txt";
// Create a request to copy the object. 
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcObjectKey, destBucketName, destObjectKey);

// ObjectMetadata objectMetadata = new ObjectMetadata();
// Specify the access control list (ACL) of the object. In this example, the ACL is set to private. 
// objectMetadata.setHeader("x-oss-object-acl", "private");
// Specify the storage class of the object. In this example, the storage class is set to Standard. 
// objectMetadata.setHeader("x-oss-storage-class", "Standard");
// Specify whether the CopyObject operation overwrites an existing object that has the same name. In this example, this parameter is set to true, which specifies that the CopyObject operation does not overwrite an existing object that has the same name. 
// objectMetadata.setHeader("x-oss-forbid-overwrite", "true");
// If the ETag value of the source object is the same as the ETag value that is specified in the request, OSS copies the object. 
// objectMetadata.setHeader("x-oss-copy-source-if-match", "5B3C1A2E053D763E1B002CC607C5****");
// Specify the path of the source object. 
// objectMetadata.setHeader("x-oss-copy-source", "/examplebucket/recode-test.txt");
// If the ETag value of the source object is different from the ETag value that is specified in the request, OSS copies the object. 
// objectMetadata.setHeader("x-oss-copy-source-if-none-match", "5B3C1A2E053D763E1B002CC607C5****");
// If the time that is specified in the request is equal to or later than the time when the object is modified, OSS copies the object. 
// objectMetadata.setHeader("x-oss-copy-source-if-unmodified-since", "2021-12-09T07:01:56.000Z");
// If the source object is modified after the time specified in the request, OSS copies the object. 
// objectMetadata.setHeader("x-oss-copy-source-if-modified-since", "2021-12-09T07:01:56.000Z");
// Specify the method that is used to configure the metadata of the destination object. In this example, the method is set to COPY, which specifies that the metadata of the source object is copied to the destination object. 
// objectMetadata.setHeader("x-oss-metadata-directive", "COPY");
// Specify the server-side encryption algorithm that is used to encrypt the destination object when the object is created. 
// objectMetadata.setHeader("x-oss-server-side-encryption", "SSE-KMS");
// Specify the customer master key (CMK) that is managed by Key Management Service (KMS). This parameter takes effect only if you set x-oss-server-side-encryption to KMS. 
// objectMetadata.setHeader("x-oss-server-side-encryption-key-id", "9468da86-3509-4f8d-a61e-6eab1eac****");
// Specify tags for the object. You can specify multiple tags at a time. 
// objectMetadata.setHeader("x-oss-tagging", "a:1");
// Specify the method that is used to configure tags for the destination object. In this example, the method is set to COPY, which specifies that the tags of the source object are copied to the destination object. 
// objectMetadata.setHeader("x-oss-tagging-directive", "COPY");

// Copy the object in asynchronous mode. 
OSSAsyncTask copyTask = oss.asyncCopyObject(copyObjectRequest, new OSSCompletedCallback<CopyObjectRequest, CopyObjectResult>() {
    @Override
    public void onSuccess(CopyObjectRequest request, CopyObjectResult result) {
        Log.d("copyObject", "copy success!");
    }

    @Override
    public void onFailure(CopyObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle request exceptions. 
        if (clientExcepion != null) {
            // Handle client-side exceptions, such as network exceptions. 
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle server-side exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
OSSCopyObjectRequest * copy = [OSSCopyObjectRequest new];
// Specify the name of the source bucket. 
copy.sourceBucketName = @"sourcebucket";
// Specify the full path of the source object. 
copy.sourceObjectKey = @"dir1/srcobject.txt";
// Specify the name of the destination bucket. 
copy.bucketName = @"destbucket";
// Specify the full path of the destination object. 
copy.objectKey = @"dir2/destobject.txt";
NSMutableDictionary *objectMeta = [NSMutableDictionary dictionary];
// Specify the access control list (ACL) of the destination object. In this example, the ACL of the destination object is set to private. 
[objectMeta setValue:@"x-oss-object-acl" forKey:@"public-read"];
// Specify the storage class of the destination object. In this example, the storage class of the destination object is set to Standard. 
[objectMeta setValue:@"x-oss-storage-class" forKey:@"Standard"];
// Specify whether to overwrite an existing object that has the same names. If x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. 
// If x-oss-forbid-overwrite is set to false, an existing object with the same name is overwritten. If x-oss-forbid-overwrite is set to true, an existing object that has the same name is not overwritten. If an existing object has the same name, an error is reported. 
[objectMeta setValue:@"x-oss-forbid-overwrite" forKey:@"true"];
// If the ETag value of the source object is the same as the ETag value that you specified in the request, the object is copied. 
[objectMeta setValue:@"x-oss-copy-source-if-match" forKey:@"5B3C1A2E053D763E1B002CC607C5****"];
// If the ETag value of the source object is different from the ETag value that you specified in the request, the object is copied. 
[objectMeta setValue:@"x-oss-copy-source-if-none-match" forKey:@"5B3C1A2E053D763E1B002CC607C5****"];
// If the object is modified at 07:01:56.000, December 09, 2021 or earlier in UTC, the object is copied. 
[objectMeta setValue:@"x-oss-copy-source-if-unmodified-since" forKey:@"2021-12-09T07:01:56.000Z"];
// If the object is modified after 07:01:56.000, December 15, 2021 in UTC, the object is copied. 
[objectMeta setValue:@"x-oss-copy-source-if-modified-since" forKey:@"2021-12-15T07:01:56.000Z"];
// Copy the metadata of the source object to the destination object. 
[objectMeta setValue:@"x-oss-metadata-directive" forKey:@"COPY"];
// Copy the tags of the source object to the destination object. 
[objectMeta setValue:@"x-oss-tagging-directive" forKey:@"Copy"];
// Specify the server-side encryption algorithm that is used to encrypt the destination object when OSS creates the object. 
[objectMeta setValue:@"x-oss-server-side-encryption" forKey:@"KMS"];
// Specify the customer master key (CMK) that is managed by Key Management Service (KMS). This parameter takes effect only when x-oss-server-side-encryption is set to KMS. 
[objectMeta setValue:@"x-oss-server-side-encryption-key-id" forKey:@"9468da86-3509-4f8d-a61e-6eab1eac****"];
copy.objectMeta = objectMeta;


OSSTask * task = [client copyObject:copy];
[task continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"copy object success!");
    } else {
        NSLog(@"copy object failed, error: %@" , task.error);
    }
    return nil;
}];
// Implement synchronous blocking to wait for the task to complete. 
//   [task waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
    
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the source bucket. Example: srcexamplebucket. */
    std::string SourceBucketName = "srcexamplebucket";
    /* Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. Example: destbucket. */
    std::string CopyBucketName = "destbucket";
    /* Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. */
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. */
    std::string CopyObjectName = "destdir/destobject.txt";

    /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    CopyObjectRequest request(CopyBucketName, CopyObjectName);
    request.setCopySource(SourceBucketName, SourceObjectName);

    /* Copy the object. */
    auto outcome = client.CopyObject(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "CopyObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the source bucket. */
const char *source_bucket_name = "yourSourceBucketName";
/* Specify the full path of the source object. Do not include the bucket name in the full path. */
const char *source_object_name = "yourSourceObjectName";
/* Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket. */
const char *dest_bucket_name = "yourDestBucketName";
/* Specify the full path of the destination object. Do not include the bucket name in the full path. */
const char *dest_object_name = "yourDestObjectName";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Specify two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Specify network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t source_bucket;
    aos_string_t source_object;
    aos_string_t dest_bucket;
    aos_string_t dest_object;
    aos_table_t *headers = NULL;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&source_bucket, source_bucket_name);
    aos_str_set(&source_object, source_object_name);
    aos_str_set(&dest_bucket, dest_bucket_name);
    aos_str_set(&dest_object, dest_object_name);
    headers = aos_table_make(pool, 0);
    /* Copy the object. */
    resp_status = oss_copy_object(oss_client_options, &source_bucket, &source_object, &dest_bucket, &dest_object, headers, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("copy object succeeded\n");
    } else {
        printf("copy object failed\n");
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
  # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')

# Copy the object and object metadata. 
bucket.copy_object(
  # In this example, srcobject.txt in the source bucket is copied to destobject.txt in the destination bucket. 
  'destobject.txt', 'srcobject.txt',
  :meta_directive => Aliyun::OSS::MetaDirective::COPY)

# Copy the object and overwrite the original metadata. 
bucket.copy_object(
  'destobject.txt', 'srcobject.txt',
  :metas => {'year' => '2017'},
  :meta_directive => Aliyun::OSS::MetaDirective::REPLACE)                        
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region         string // The region.
	srcBucketName string // The name of the source bucket.
	srcObjectName string // The name of the source object.
	destBucketName string // The name of the destination bucket.
	destObjectName string // The name of the destination object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&srcBucketName, "src-bucket", "", "The name of the source bucket.")
	flag.StringVar(&srcObjectName, "src-object", "", "The name of the source object.")
	flag.StringVar(&destBucketName, "dest-bucket", "", "The name of the destination bucket.")
	flag.StringVar(&destObjectName, "dest-object", "", "The name of the destination object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the source bucket name is empty.
	if len(srcBucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// If the destination bucket name is not specified, the source bucket name is used.
	if len(destBucketName) == 0 {
		destBucketName = srcBucketName
	}

	// Check whether the source object name is empty.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source object name required")
	}

	// Check whether the destination object name is empty.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to copy an object.
	request := &oss.CopyObjectRequest{
		Bucket:       oss.Ptr(destBucketName), // The name of the destination bucket.
		Key:          oss.Ptr(destObjectName), // The name of the destination object.
		SourceKey:     oss.Ptr(srcObjectName), // The name of the source object.
		SourceBucket: oss.Ptr(srcBucketName), // The name of the source bucket.
	}

	// Copy the source object and process the results.
	result, err := client.CopyObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to copy object %v", err)
	}
	log.Printf("copy object result:%#v\n", result)
}
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="copy object sample")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the destination bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the destination object. This parameter is required.
parser.add_argument('--key', help='The name of the destination object.', required=True)
# Specify the --source_key parameter, which specifies the name of the source object. This parameter is required.
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# Specify the --source_bucket parameter, which specifies the name of the source bucket. This parameter is required.
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)

def main():
    # Parse the command line parameters.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Copy objects.
    result = client.copy_object(oss.CopyObjectRequest(
        bucket=args.bucket,  # The name of the destination bucket.
        key=args.key,  # The key name of the destination object.
        source_key=args.source_key,  # The key name of the source object.
        source_bucket=args.source_bucket,  # The name of the source bucket.
    ))

    # Output the result information of the copy operation.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' hash crc64: {result.hash_crc64},'
          f' source version id: {result.source_version_id},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' last modified: {result.last_modified},'
          f' etag: {result.etag},'
    )

# Call the main function when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry points in the main function of the script when the script is directly run.
<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the destination bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the destination object.
    "src-bucket" => ['help' => 'The name of the source bucket', 'required' => False], // (Optional) Specify the name of the source bucket.
    "src-key" => ['help' => 'The name of the source object', 'required' => True], // (Required) Specify the name of the source object.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required. 
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command-line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // Region in which the bucket is located.
$bucket = $options["bucket"]; // Name of the destination bucket.
$key = $options["key"];       // Name of the destination object.
$srcKey = $options["src-key"]; // Name of the source object.

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a CopyObjectRequest object to copy the source object.
$request = new Oss\Models\CopyObjectRequest(
            bucket: $bucket,
            key: $key);

if (!empty($options["src-bucket"])) {
    $request->sourceBucket = $options["src-bucket"]; // If the source bucket name is provided, specify the sourceBucket parameter.
}
$request->sourceKey = $srcKey; // Specify the name of the source object.

// Copy the source object.
$result = $client->copyObject($request);

// Output the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used to debug or trace a request.
);

Use ossutil

You can copy objects by using ossutil. For more information, see Install ossutil.

The following example demonstrates how to copy srcObject from srcBucket to examplebucket.

ossutil api copy-object --bucket examplebucket --key exampleobject --copy-source /srcBucket/srcObject

For more information, see copy-object.

Related API operation

The methods described in this topic are based on the CopyObject API operation, which you can directly call if your business requires a high level of customization. To directly call an API, you must include the signature calculation in your code.