This topic describes how to copy an object in a versioning-enabled bucket in Object Storage Service (OSS). You can call CopyObject to copy an object up to 1 GB in size and call UploadPartCopy to copy an object larger than 1 GB in size.
Usage notes
In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.
In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.
To copy an object, you must have the
oss:GetObject
andoss:PutObject
permissions. For more information, see Attach a custom policy to a RAM user.
Copy a small object
You can call CopyObject to copy an object that is up to 1 GB in size from a source bucket to a destination bucket within the same region.
By default, the x-oss-copy-source header specifies the current version of the object to copy. If the current version of the object is a delete marker, OSS returns HTTP 404 status code. The HTTP status code indicates that the object does not exist. You can add versionId to the x-oss-copy-source request header to copy the specified object version. Delete markers cannot be copied.
You can copy a previous version of an object to the same bucket. The copied previous version becomes the current version of the object. This way, the previous version of the object is recovered.
If versioning is enabled for the destination bucket, OSS generates a unique version ID for the destination object. The version ID is returned as the value of the x-oss-version-id header in the response. If versioning is disabled or suspended for the destination bucket, OSS generates a version whose ID is null for the destination object and overwrites the original version whose ID is null.
Appendable objects cannot be copied to a destination bucket for which versioning is enabled or suspended.
The following sample code provides an example on how to copy a small object:
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 = "yourEndpoint";
// 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.
var sourceBucket = "yourSourceBucketName";
// Specify the full path of the source object. Do not include the bucket name in the full path.
var sourceObject = "yourSourceObjectName";
// Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket.
var targetBucket = "yourDestBucketName";
// Specify the full path of the destination object. Do not include the bucket name in the full path.
var targetObject = "yourDestObjectName";
// Specify the version ID of the source object.
var versionid = "yourArchiveObjectVersionid";
// 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();
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 source object overwrites the metadata of the destination object.
NewObjectMetadata = metadata,
// Specify the version ID of the object.
SourceVersionId = versionid
};
// Copy the object.
var result = client.CopyObject(req);
Console.WriteLine("Copy object succeeded, vesionid:{0}", result.VersionId);
}
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);
}
Copy a large object
To copy an object that is larger than 1 GB in size, you need to split the object into parts and copy the parts by using UploadPartCopy.
By default, the UploadPartCopy operation uploads a part by copying data from the current version of the specified object. You can add a version ID to the x-oss-copy-source header to copy the specified version of the object. Example: x-oss-copy-source: /SourceBucketName/SourceObjectName?versionId=CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****.
The value of the SourceObjectName parameter must be URL-encoded. The version ID of the copied object is returned as the value of the x-oss-copy-source-version-id header in the response.
If a version ID is not specified in the request and the current version of the source object is a delete marker, OSS returns 404 Not Found. If a version ID is specified in the request and the specified version of the source object is a delete marker, OSS returns 400 Bad Request.
The following sample code provides an example on how to copy a large object by using multipart copy:
using System;
using System.Collections.Generic;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace Samples
{
public class Program
{
public static void Main(string[] args)
{
// 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.
var sourceBucket = "yourSourceBucketName";
// Specify the full path of the source object. Do not include the bucket name in the full path.
var sourceObject = "yourSourceObjectName";
// Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket.
var targetBucket = "yourDestBucketName";
// Specify the full path of the destination object. Do not include the bucket name in the full path.
var targetObject = "yourDestObjectName";
// Specify the version ID of the source object.
var sourceObjectVersionid = "yourSourceObjectVersionid";
var partSize = 50 * 1024 * 1024;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// Initiate a multipart copy task. You can call the InitiateMultipartUploadRequest operation to specify the metadata of the destination object.
var initRequest = new InitiateMultipartUploadRequest(targetBucket, targetObject);
var result = client.InitiateMultipartUpload(initRequest);
// Display the upload ID.
var uploadId = result.UploadId;
Console.WriteLine("Init multipart upload succeeded, Upload Id: {0}", result.UploadId);
// Calculate the total number of parts.
var request = new GetObjectMetadataRequest(sourceBucket, sourceObject)
{
// Specify the version ID of the object.
VersionId = sourceObjectVersionid
};
var metadata = client.GetObjectMetadata(request);
var fileSize = metadata.ContentLength;
var partCount = (int)fileSize / partSize;
if (fileSize % partSize != 0)
{
partCount++;
}
// Start the multipart copy task.
var partETags = new List<PartETag>();
for (var i = 0; i < partCount; i++)
{
var skipBytes = (long)partSize * i;
var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
// Create an UploadPartCopyRequest request. You can call the UploadPartCopyRequest operation to specify conditions.
var uploadPartCopyRequest = new UploadPartCopyRequest(targetBucket, targetObject, sourceBucket, sourceObject, uploadId)
{
PartSize = size,
PartNumber = i + 1,
// Use BeginIndex to find the start position to upload the part.
BeginIndex = skipBytes,
// Specify the version ID of the object.
VersionId = sourceObjectVersionid
};
// Call the uploadPartCopy operation to copy each part.
var uploadPartCopyResult = client.UploadPartCopy(uploadPartCopyRequest);
Console.WriteLine("UploadPartCopy : {0}", i);
partETags.Add(uploadPartCopyResult.PartETag);
}
// Complete the multipart copy task.
var completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(targetBucket, targetObject, uploadId);
// partETags is a list of partETag. OSS verifies each part after it receives partETags. After all parts are verified, OSS combines these parts into a complete object.
foreach (var partETag in partETags)
{
completeMultipartUploadRequest.PartETags.Add(partETag);
}
var completeMultipartUploadResult = client.CompleteMultipartUpload(completeMultipartUploadRequest);
Console.WriteLine("CompleteMultipartUpload succeeded, vesionid:{0}", completeMultipartUploadResult.VersionId);
}
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);
}
}
}
}
References
For more information about the API operation that you can call to copy a small object, see CopyObject.
For more information about the API operation that you can call to copy a large object, see UploadPartCopy.