All Products
Search
Document Center

Object Storage Service:Copy objects

Last Updated:Feb 29, 2024

You can copy an object from a source bucket to a destination bucket that is located in the same region without modifying the content of the object.

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.

  • Appendable objects cannot be copied.

Usage notes

  • If you want to copy a large number of objects and set the storage class of the destination objects to Deep Cold Archive, high PUT request fees are generated. We recommend that you configure lifecycle rules to convert the storage class of the objects to Deep Cold Archive. This helps reduce PUT request fees. For more information about lifecycle rules, see Lifecycle rules based on the last modified time.

  • 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 Overview.

    • 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.

Procedure

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 Use ossbrowser.

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.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        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 specified in the request is the same as or later than the modification time of the object, 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();
            }
        }
    }
}                 
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.  
$accessKeyId = getenv("OSS_ACCESS_KEY_ID"); 
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the source bucket. Example: srcexamplebucket. 
$from_bucket = "srcexamplebucket";
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/exampleobject.txt. 
$from_object = "srcdir/exampleobject.txt";
// Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket. Example: destexamplebucket. 
// If you copy an object within a bucket, make sure that you specify the same bucket name for the source bucket and destination bucket. 
$to_bucket = "destexamplebucket";
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/exampleobject.txt. 
$to_object = "destdir/exampleobject.txt";

$options = array(
    'headers'=>array(
      // Specify whether the CopyObject operation overwrites an object that has the same name as the source bucket. In this example, this parameter is set to true. The value true indicates that the operation does not overwrite an object that has the same name as the source bucket. 
      // 'x-oss-forbid-overwrite' => 'true',
      // If the ETag value that you specify in the request is the same as the ETag value of the source object, OSS copies the object and returns 200 OK. 
      // 'x-oss-copy-source-if-match' => '5B3C1A2E053D763E1B002CC****',
      // 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. 
      // 'x-oss-copy-source-if-none-match' => '5B3C1A2E053D763E1B002CC****',
      // If the time specified in the request is the same as or later than the modification time of the object, OSS copies the object and returns 200 OK. 
      // 'x-oss-copy-source-if-unmodified-since' => gmdate('2021-12-09T07:01:56.000Z'),
      // If the time that is specified in the request is earlier than the actual time when the object is modified, OSS copies the object and returns 200 OK. 
      // 'x-oss-copy-source-if-modified-since' => gmdate('2021-12-09T07:01:56.000Z'),
      // Specify the method that is used to configure the metadata of the destination object. If you set the method to COPY, the metadata of the source object is copied to the destination object. 
      // 'x-oss-metadata-directive' => 'COPY',
      // Specify the server-side encryption algorithm that is used to encrypt the destination object when OSS creates the object. 
      // 'x-oss-server-side-encryption' => 'KMS',
      // Specify the CMK that is managed by KMS. This parameter takes effect only when x-oss-server-side-encryption is set to KMS. 
      // 'x-oss-server-side-encryption-key-id' => '9468da86-3509-4f8d-a61e-6eab****',
      // Specify the ACL of the destination object when OSS creates the object. In this example, the ACL is set to Private, which indicates that only the owner of the object and authorized users have read and write permissions on the object. 
      // 'x-oss-object-acl' => 'private',
      // Specify the storage class of the destination object. In this example, the storage class is set to Standard. 
      // 'x-oss-storage-class' => 'Standard',
      // Specify tags for the object. You can specify multiple tags for the object at the same time. 
      // 'x-oss-tagging' => 'k1=v1&k2=v2&k3=v3',
      // Specify the method that is used to configure tags for the destination object. If you set the method to COPY, the tags of the source object are copied to the destination object. 
      // 'x-oss-tagging-directive' => 'COPY',
    ),
);

try{
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

    $ossClient->copyObject($from_bucket, $from_object, $to_bucket, $to_object);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            
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,
  // 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 time that is specified in the request is later than the time when the object is modified, OSS copies the object and returns 200 OK. 
        '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()
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 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. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the name of the source bucket. Example: srcexamplebucket. 
src_bucket_name = 'srcexamplebucket'
# Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket. Example: destexamplebucket. 
# If you copy an object within a bucket, make sure that you specify the same bucket name for the source bucket and destination bucket. 
dest_bucket_name = 'destexamplebucket'
# 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. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', dest_bucket_name)

# Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt. 
src_object_name = 'srcexampleobject.txt'
# Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject.txt. 
dest_object_name = 'destexampleobject.txt'

# headers = dict()
# 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. 
# headers['x-oss-forbid-overwrite'] = 'true'
# Specify the path of the source object. 
# headers[OSS_COPY_OBJECT_SOURCE] = '/example-bucket-by-util/recode-test.txt'
# 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 and returns 200 OK. 
# headers['x-oss-copy-source-if-match'] = '5B3C1A2E053D763E1B002CC607C5****'
# If the ETag value of the source object is different from the ETag value that is specified in the request, OSS copies the object and returns 200 OK. 
# headers['x-oss-copy-source-if-none-match'] = '5B3C1A2E053D763E1B002CC607C5****'
# If the time that is specified in the request is equal to or later than the actual modified time of the object, OSS copies the object and returns 200 OK. 
# headers['x-oss-copy-source-if-unmodified-since'] = '2021-12-09T07:01:56.000Z'
# If the source object is modified after the time that is specified in the request, OSS copies the object. 
# headers['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. If you set the method to COPY, the metadata of the source object is copied to the destination object. 
# headers[OSS_METADATA_DIRECTIVE] = 'COPY'
# Specify the server-side encryption algorithm that is used to encrypt the destination object when OSS creates the destination object. 
# headers[OSS_SERVER_SIDE_ENCRYPTION] = '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. 
# headers['x-oss-server-side-encryption-key-id'] = '9468da86-3509-4f8d-a61e-6eab1eac****'
# Specify the access control list (ACL) of the destination object. In this example, this parameter is set to OBJECT_ACL_PRIVATE, which indicates that only the object owner and authorized users have read and write permissions on the object. 
# headers[OSS_OBJECT_ACL] = oss2.OBJECT_ACL_PRIVATE
# Specify the storage class of the destination object. In this example, the storage class is set to Standard. 
# headers['x-oss-storage-class'] = oss2.BUCKET_STORAGE_CLASS_STANDARD
# Specify tags for the object. You can specify multiple tags for the object at the same time. 
# headers[OSS_OBJECT_TAGGING] = 'k1=v1&k2=v2&k3=v3'
# Specify the method that is used to configure the tag of the destination object. If you set the method to COPY, the tags of the source object are copied to the destination object. 
# headers[OSS_OBJECT_TAGGING_COPY_DIRECTIVE] = 'COPY'
# result = bucket.copy_object(src_bucket_name, src_object_name, dest_object_name, headers=headers)

# Copy the object from the source bucket to the destination bucket. 
result = bucket.copy_object(src_bucket_name, src_object_name, dest_object_name)

# View the response. If HTTP status code 200 is returned, the operation is successful. 
print('result.status:', result.status)
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";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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 in the same region as the source bucket. 
String destBucketName = "destbucket";
// Specify the full path of the destination object. 
String destObjectKey = "dir2/destobject.txt";
// Construct a request to copy the object. 
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcObjectKey, destBucketName, destObjectKey);

// ObjectMetadata objectMetadata = new ObjectMetadata();
// Set 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 object with the same name. In this example, this parameter is set to true, which indicates that the object with the same name cannot be overwritten. 
// 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 that is 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 indicates 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. 
// 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 when 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 indicates 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 errors. 
            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());
        }
    }
});
package main

import (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
    "time"
)

func main() {
    // 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. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"
    // Specify the full path of the source object. Example: srcdir/srcobject.jpg. 
    objectName := "srcdir/srcobject.jpg"
    // Specify the full path of the destination object. Example: destdir/destobject.jpg. 
    destObjectName := "destdir/destobject.jpg"

    // Obtain the bucket information. 
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        fmt.Println("Error:", err)

        os.Exit(-1)
    }

    // 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 tags of the source object to the destination object. 
        // oss.TaggingDirective(oss.TaggingCopy),
        // Set the access control list (ACL) of the destination object to private when OSS creates the destination object.     
        // oss.ObjectACL(oss.ACLPrivate),
        // 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. 
        //oss.ServerSideEncryptionKeyID("9468da86-3509-4f8d-a61e-6eab1eac****"),
        // Specify the server-side encryption algorithm that is used to encrypt the destination object when OSS creates the 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 an object that has the same name as the source bucket. In this example, this parameter is set to true. The value true indicates that the operation does not overwrite an object that has the same name as the source bucket. 
        // oss.ForbidOverWrite(true),
        // If the ETag value that you specify in the request is the same as the ETag value of the source object, OSS copies the object and returns 200 OK. 
        //oss.CopySourceIfMatch("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. 
        //oss.CopySourceIfNoneMatch("5B3C1A2E053D763E1B002CC607C5****"),
        // If the time specified in the request is earlier than the actual time when the object is modified, OSS copies the object and returns 200 OK. 
        //oss.CopySourceIfModifiedSince(2021-12-09T07:01:56.000Z),
        // If the time specified in the request is the same as or later than the modification time of the object, OSS copies the object and returns 200 OK. 
        //oss.CopySourceIfUnmodifiedSince(2021-12-09T07:01:56.000Z),
        // Specify the storage class of the destination object. In this example, the storage class is set to Standard. 
        //oss.StorageClass("Standard"),
        }

    // Overwrite the metadata of the source object by using the metadata that you specify in the request. 
    _, err = bucket.CopyObject(objectName, destObjectName, options...)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}
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 the existing object that has the same name. By default, if x-oss-forbid-overwrite is not specified, the existing object that has the same name is overwritten. 
// If x-oss-forbid-overwrite is set to false, the existing object that has the same name is overwritten. If x-oss-forbid-overwrite is set to true, the 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;
}];
#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 = "https://oss-cn-hangzhou.aliyuncs.com";
    /* 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;
    /* 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);

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

Use ossutil

For more information about how to use ossutil to copy an object, see Copy objects.

Use the OSS API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you need to include the signature calculation in your code. For more information, see CopyObject.