Tous les produits
Search
Centre de documentation

Object Storage Service:Copy objects

Dernière mise à jour :Aug 18, 2026

Vous pouvez copier un objet d'un bucket source vers un bucket de destination dans la même région tout en conservant son contenu. Cette opération sert couramment à la sauvegarde et à la migration des données.

Limites

La copie d'objets entre différentes régions n'est pas prise en charge. Par exemple, vous ne pouvez pas copier un objet d'un bucket situé dans la région China (Hangzhou) vers un bucket situé dans la région China (Shanghai).

Remarques sur l'utilisation

  • Si vous copiez un grand nombre d'objets et définissez immédiatement leur classe de stockage sur Deep Cold Archive, des frais de requête PUT élevés peuvent s'appliquer. Pour réduire les coûts, configurez des règles de cycle de vie afin de transférer ces objets vers la classe de stockage Deep Cold Archive.

  • Vous devez disposer d'autorisations de lecture sur l'objet source ainsi que d'autorisations de lecture et d'écriture sur le bucket de destination. Sinon, l'opération de copie échoue.

  • Lors de la copie d'un objet, assurez-vous qu'aucune politique de rétention n'est configurée sur les buckets source et de destination. Sinon, l'erreur The object you specified is immutable. s'affiche.

  • Par défaut, si vous copiez un objet vers un bucket de destination où un objet portant le même nom existe déjà, ce dernier est écrasé. Pour éviter tout écrasement inattendu, adoptez l'une des méthodes suivantes afin de protéger vos objets.

    • Activez le versioning

      Une fois le versioning activé, les objets supprimés ou écrasés sont conservés sous forme de versions précédentes. Vous pouvez restaurer ces versions à tout moment. Pour plus d'informations, consultez Présentation.

    • Incluez un paramètre interdisant l'écrasement dans la requête de copie

      Ajoutez l'en-tête x-oss-forbid-overwrite dans la requête de copie et définissez sa valeur sur true. Si un objet portant le même nom que celui que vous souhaitez copier existe déjà dans le bucket de destination, la copie échoue et l'erreur FileAlreadyExists est renvoyée.

Procédure

Using the graphical management tool ossbrowser

ossbrowser permet de copier des objets dont la taille est inférieure à 5 Go. Pour plus d'informations sur l'utilisation d'ossbrowser pour copier des objets, consultez Opérations courantes.

Use Alibaba Cloud SDKs

Les exemples de code suivants montrent comment utiliser les SDK courants pour appeler l'opération CopyObject et copier un objet de moins de 1 Go. Pour savoir comment utiliser d'autres SDK afin de copier un objet inférieur à 1 Go, ou comment appeler l'opération UploadPartCopy pour copier un objet supérieur à 1 Go, consultez Présentation des SDK.

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 {
        // The China (Hangzhou) region is used as an example. Specify the 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. The full path cannot contain the bucket name.
        String sourceKey = "srcexampleobject.txt";
        // Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket.
        String destinationBucketName = "desexamplebucket";
        // Specify the full path of the destination object. The full path cannot contain the bucket name.
        String destinationKey = "desexampleobject.txt";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        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);

            // Set new file metadata.
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("text/plain");
            // Specify whether to overwrite the destination object if it has the same name. In this example, this parameter is set to true, which indicates that the destination object cannot be overwritten.
            // meta.setHeader("x-oss-forbid-overwrite", "true");
            // Specify the source address for the copy operation.
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE, "/examplebucket/recode-test.txt");
            // If the ETag of the source object matches the specified ETag, the copy operation is performed and 200 OK is returned.
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_MATCH, "5B3C1A2E053D763E1B002CC607C5****");
            // If the ETag of the source object does not match the specified ETag, the copy operation is performed and 200 OK is returned.
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_NONE_MATCH, "5B3C1A2E053D763E1B002CC607C5****");
            // 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.
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_UNMODIFIED_SINCE, "2021-12-09T07:01:56.000Z");
            // If the source object has been modified after the specified time, the copy operation is performed.
            // meta.setHeader(OSSHeaders.COPY_OBJECT_SOURCE_IF_MODIFIED_SINCE, "2021-12-09T07:01:56.000Z");
            // Specify how to set the metadata of the destination object. In this example, this parameter is set to COPY, which indicates 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 OSS uses to create the destination object.
            // meta.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
            // The customer master key (CMK) managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
            // meta.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION_KEY_ID, "9468da86-3509-4f8d-a61e-6eab1eac****");
            // Specify the access permissions for the destination object when it is created in OSS. In this example, this parameter is set to Private, which indicates that only the object owner and authorized users have read and write permissions. Other users cannot access the object.
            // meta.setHeader(OSSHeaders.OSS_OBJECT_ACL, CannedAccessControlList.Private);
            // Specify the storage class of the object. In this example, this parameter is set to Standard.
            // meta.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard);
            // Specify the tags for the object. You can specify multiple tags.
            // meta.setHeader(OSSHeaders.OSS_TAGGING, "a:1");
            // Specify how to set the tags for the destination object. In this example, this parameter is set to COPY, which indicates 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 file.
            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 destination object and source object. Do not include the bucket name in the full paths.
    // Specify HTTP headers and custom 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. Other users do not have permissions to access 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 for the region where the bucket is located. For example, if the bucket is 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. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt.
var sourceObject = "srcdir/scrobject.txt";
// Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket.
var targetBucket = "destbucket";
// Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt.
var targetObject = "destdir/destobject.txt";
// Specify the region where the bucket is located. For example, if the bucket is 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 as needed.
var conf = new ClientConfiguration();

// Use Signature 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();
    // Set custom metadata. Custom metadata is a key-value pair. For example, set the key to mk1 and the value to mv1.
    metadata.UserMetadata.Add("mk1", "mv1");
    metadata.UserMetadata.Add("mk2", "mv2");
    var req = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject)
    {
        // If NewObjectMetadata is null, the metadata of the source object is copied (COPY mode). If NewObjectMetadata is not null, the metadata of the source object is overwritten (REPLACE mode).
        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 = "src-bucket";
// Specify the full path of the object in the source bucket.
String srcObjectKey = "dir1/source-object.txt";
// Specify the name of the destination bucket, which must be in the same region as the source bucket.
String destBucketName = "dest-bucket";
// Specify the full path of the object in the destination bucket.
String destObjectKey = "dir2/destination-object.txt";
// Create a copy request.
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");
// Set 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 to overwrite an existing object that has the same name in the destination bucket. In this example, the value is set to true, which indicates that the existing object cannot be overwritten.
// objectMetadata.setHeader("x-oss-forbid-overwrite", "true");
// The copy operation is performed only if the ETag of the source object matches the specified ETag.
// objectMetadata.setHeader("x-oss-copy-source-if-match", "5B3C1A2E053D763E1B002CC607C5****");
// Specify the source address for the copy operation.
// objectMetadata.setHeader("x-oss-copy-source", "/example-bucket/recode-test.txt");
// The copy operation is performed only if the ETag of the source object does not match the specified ETag.
// objectMetadata.setHeader("x-oss-copy-source-if-none-match", "5B3C1A2E053D763E1B002CC607C5****");
// The copy operation is performed only if the actual modification time of the object is earlier than or the same as the specified time.
// objectMetadata.setHeader("x-oss-copy-source-if-unmodified-since", "2021-12-09T07:01:56.000Z");
// The copy operation is performed only if the source object was modified after the specified time.
// objectMetadata.setHeader("x-oss-copy-source-if-modified-since", "2021-12-09T07:01:56.000Z");
// Specify how to configure the metadata of the destination object. In this example, the value 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 OSS uses to create the destination object.
// objectMetadata.setHeader("x-oss-server-side-encryption", "SSE-KMS");
// The customer master key (CMK) managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
// objectMetadata.setHeader("x-oss-server-side-encryption-key-id", "9468da86-3509-4f8d-a61e-6eab1eac****");
// Specify the tags of the object. You can specify multiple tags at the same time.
// objectMetadata.setHeader("x-oss-tagging", "a:1");
// Specify how to configure the tags of the destination object. In this example, the value 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");

// Perform an asynchronous copy.
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) {
        // The request failed.
        if (clientExcepion != null) {
            // A client exception occurred, such as a network exception.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A server-side exception occurred.
            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 object in the source bucket.
copy.sourceObjectKey = @"dir1/srcobject.txt";
// Specify the name of the destination bucket.
copy.bucketName = @"destbucket";
// Specify the full path of the object in the destination bucket.
copy.objectKey = @"dir2/destobject.txt";
NSMutableDictionary *objectMeta = [NSMutableDictionary dictionary];
// Set the access control list (ACL). In this example, the value is set to public-read.
[objectMeta setValue:@"public-read" forKey:@"x-oss-object-acl"];
// Set the storage class. In this example, the value is set to Standard.
[objectMeta setValue:@"Standard" forKey:@"x-oss-storage-class"];
// Specify whether to overwrite an object that has the same name. If you do not specify x-oss-forbid-overwrite, the object is overwritten by default.
// If you set x-oss-forbid-overwrite to false, the object can be overwritten. If you set x-oss-forbid-overwrite to true, the object cannot be overwritten. If an object with the same name exists, an error is reported.
[objectMeta setValue:@"true" forKey:@"x-oss-forbid-overwrite"];
// The copy operation is performed only if the ETag of the source object matches the ETag you provide.
[objectMeta setValue:@"5B3C1A2E053D763E1B002CC607C5****" forKey:@"x-oss-copy-source-if-match"];
// The copy operation is performed only if the ETag of the source object does not match the ETag you provide.
[objectMeta setValue:@"5B3C1A2E053D763E1B002CC607C5****" forKey:@"x-oss-copy-source-if-none-match"];
// The copy operation is performed only if the object was last modified on or before 2021-12-09T07:01:56.000Z.
[objectMeta setValue:@"2021-12-09T07:01:56.000Z" forKey:@"x-oss-copy-source-if-unmodified-since"];
// The copy operation is performed only if the object was last modified after 2021-12-15T07:01:56.000Z.
[objectMeta setValue:@"2021-12-15T07:01:56.000Z" forKey:@"x-oss-copy-source-if-modified-since"];
// Copy the metadata from the source object to the destination object.
[objectMeta setValue:@"COPY" forKey:@"x-oss-metadata-directive"];
// Copy the tags from the source object to the destination object.
[objectMeta setValue:@"Copy" forKey:@"x-oss-tagging-directive"];
// Specify the server-side encryption algorithm that OSS uses to create the destination object.
[objectMeta setValue:@"KMS" forKey:@"x-oss-server-side-encryption"];
// The customer master key (CMK) that is managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
[objectMeta setValue:@"9468da86-3509-4f8d-a61e-6eab1eac****" forKey:@"x-oss-server-side-encryption-key-id"];
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;
}];
//   Block the current thread 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"
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is 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. The full path cannot contain the bucket name. */
const char *source_object_name = "yourSourceObjectName";
/* Specify the name of the destination bucket, which must be in the same region as the source bucket. */
const char *dest_bucket_name = "yourDestBucketName";
/* Specify the full path of the destination object. The full path cannot contain the bucket name. */
const char *dest_object_name = "yourDestObjectName";
/* Set yourRegion to the Region ID of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* 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 set. */
    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"));
    // Configure the following two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specifies whether a CNAME is used. 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set 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 at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool (pool) for memory management is equivalent to apr_pool_t. The implementation code is in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is NULL, which indicates that the new memory pool does not inherit from another memory pool. */
    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 memory to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize 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 file. */
    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 releases the memory allocated to resources during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
  # Set the endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is 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 bucket name. Example: examplebucket.
bucket = client.get_bucket('examplebucket')

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

# Copy the object and overwrite its 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

ossutil permet également de copier des objets. Pour plus d'informations sur l'installation d'ossutil, consultez Installer ossutil.

L'exemple suivant montre comment copier srcObject depuis le bucket srcBucket vers le bucket examplebucket et l'enregistrer sous le nom exampleobject.

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

Pour plus d'informations sur cette commande, consultez copy-object.

Opération API associée

Les opérations ci-dessus reposent sur l'API CopyObject. Pour une personnalisation avancée, appelez directement l'API REST. Vous devrez alors calculer manuellement la signature de la requête. Pour plus d'informations, consultez CopyObject.