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 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.
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";
// 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.
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 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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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 = new EnvironmentVariableCredentialsProvider();
// 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 located 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 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',
// 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 you set x-oss-server-side-encryption 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 one or more tags for the destination object.
// '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{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
$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,
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 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.ProviderAuthV4(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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, dest_bucket_name, region=region)
# 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";
// 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);
c.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)
Use 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
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.