Copie objetos dentro de un mismo bucket o entre buckets de la misma región.
Precauciones
Para copiar un archivo, debe contar con permisos de lectura sobre el archivo de origen y permisos de lectura y escritura en el bucket de destino.
No se admite la copia entre regiones. Por ejemplo, no es posible copiar un archivo de un bucket en la región China (Hangzhou) a otro en la región China (Qingdao).
El tamaño del archivo que se va a copiar no puede superar 1 GB.
Antes de ejecutar el código de ejemplo de este tema, cree una instancia de OSSClient mediante métodos como el uso de un nombre de dominio personalizado o Security Token Service (STS). Para obtener más información, consulte Initialization (Android SDK).
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene todos los permisos. Los usuarios o roles de RAM asociados a una cuenta de Alibaba Cloud no cuentan con ningún permiso de manera predeterminada. La cuenta de Alibaba Cloud o su administrador deben otorgar los permisos de operación correspondientes mediante directivas de RAM o Bucket Policy.
|
API |
Action |
Descripción |
|
CopyObject |
|
Copia objetos dentro de un mismo bucket o entre buckets de la misma región. |
|
|
||
|
|
Este permiso también es obligatorio si especifica la versión del objeto de origen mediante versionId. |
|
|
|
Estos permisos son obligatorios cuando se copian las etiquetas del objeto mediante x-oss-tagging. |
|
|
|
||
|
|
Este permiso también es obligatorio si especifica las etiquetas de una versión específica del objeto de origen mediante versionId. |
|
|
|
Estos dos permisos son obligatorios durante la copia de un objeto si los metadatos del objeto de destino contienen X-Oss-Server-Side-Encryption: KMS. |
|
|
|
Código de ejemplo
A continuación se muestra cómo copiar un archivo:
// 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());
}
}
});
Referencias
Para consultar el código de ejemplo completo sobre cómo copiar un archivo, revise el ejemplo en GitHub.
Para obtener información sobre la operación de API que permite copiar un archivo, consulte CopyObject.
Para conocer cómo inicializar una instancia de OSSClient, consulte Initialize an OSSClient instance for Android.