Todos los productos
Search
Centro de documentos

Object Storage Service:Copiar objetos (SDK de Node.js)

Última actualización: Sep 24, 2026

Copie objetos dentro de un mismo bucket o entre buckets de la misma región.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si accede a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información, consulte 配置访问凭证.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Client configuration.

  • Debe contar con permisos de lectura sobre el objeto de origen y permisos de lectura y escritura en el bucket de destino.

  • Los buckets de origen y de destino no deben tener políticas de retención configuradas. De lo contrario, la copia falla y se devuelve el error The object you specified is immutable..

  • No se admite la copia entre regiones. Por ejemplo, no es posible copiar un objeto de un bucket en China (Hangzhou) a otro en China (Qingdao).

Permisos

De forma predeterminada, una cuenta de Alibaba Cloud tiene todos los permisos. Los usuarios y 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 mediante RAM policies o Bucket Policy.

API

Action

Descripción

CopyObject

oss:GetObject

Copia objetos dentro de un mismo bucket o entre buckets de la misma región.

oss:PutObject

oss:GetObjectVersion

Si especifica la versión del objeto de origen mediante versionId, también se requiere este permiso.

oss:GetObjectTagging

Si copia las etiquetas del objeto mediante x-oss-tagging, se requieren estos permisos.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Si especifica las etiquetas de una versión concreta del objeto de origen mediante versionId, también se requiere este permiso.

kms:GenerateDataKey

Al copiar un objeto, si los metadatos del objeto de destino contienen X-Oss-Server-Side-Encryption: KMS, se requieren estos dos permisos.

kms:Decrypt

Copiar un objeto pequeño

Utilice el método copy para copiar un objeto de hasta 1 GB de tamaño dentro del mismo bucket o hacia otro bucket de la misma región.

  • Copiar un objeto dentro del mismo bucket

    A continuación se muestra un ejemplo de código para copiar un objeto dentro del mismo bucket.

    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()
  • Copiar un objeto entre buckets de la misma regiónA continuación se muestra un ejemplo de código para copiar un objeto entre buckets de la misma región.

    A continuación se muestra un ejemplo de código para copiar un objeto entre buckets de la misma regió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 destination bucket.
      bucket: 'destexamplebucket',
    });
    
    async function copySmallObjectBetweenBuckets() {
      try {
        // Specify the name of the destination object destobject.txt, the name of the source object srcobject.txt, and the name of the bucket to which the source object belongs.
        const result = await client.copy('destobject.txt', 'srcobject.txt', 'srcbucket', {
          // 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',
          },
          // 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);
      }
    }
    
    copySmallObjectBetweenBuckets()

Copiar un objeto grande

Para objetos mayores a 1 GB, utilice el método multipartUploadCopy y ejecute una copia por partes.

A continuación se muestra un ejemplo de código para copiar un objeto entre buckets de la misma regió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 destination bucket.
  bucket: "destexamplebucket",
});

async function copyLargeObjectBetweenDifferentBuckets() {
  try {
    const copyheaders = {
      // 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. Otherwise, OSS returns the HTTP status code 412 (PreconditionFailed).
      "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. Otherwise, OSS returns the HTTP status code 304 (NotModified).  
      "x-oss-copy-source-if-none-match": "5B3C1A2E053D763E1B002CC607C5****",
      // If the time that is specified in the request is later than or the same as the time when the object is modified, OSS copies the object and returns 200 OK. Otherwise, OSS returns the HTTP status code 412 (PreconditionFailed).  
      "x-oss-copy-source-if-unmodified-since": "2022-12-09T07:01:56.000Z",
      // 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. Otherwise, OSS returns the HTTP status code 304 (NotModified).
      "x-oss-copy-source-if-modified-since": "2022-12-09T07:01:56.000Z",
    };

    const headers = {
      // Specify the caching behavior of the web page when the object is downloaded.
      "Cache-Control": "no-cache",
      // Specify the name of the object when the object is downloaded.
      "Content-Disposition": "somename",
      // Specify the expiration time in milliseconds.
      Expires: "1000",
    };

    let savedCpt;
    // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject1.txt.
    const r1 = await client.multipartUploadCopy("destexampleobject1.txt", {
      // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
      sourceKey: "srcexampleobject.txt",
      // Specify the name of the source bucket. Example: sourcebucket.  
      sourceBucketName: "sourcebucket",
      copyheaders: copyheaders,
    });
    console.log(r1);

    // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject2.txt.
    const r2 = await client.multipartUploadCopy("destexampleobject2.txt", {
      // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
      sourceKey: "srcexampleobject.txt",
      // Specify the name of the source bucket. Example: sourcebucket.
      sourceBucketName: "sourcebucket",
    }, {
      // Set the number of parts that can be uploaded in parallel.
      parallel: 4,
      // Set the part size.
      partSize: 1024 * 1024,
      progress: function (p, cpt, res) {
        console.log(p);
        savedCpt = cpt;
        console.log(cpt);
        console.log(res.headers["x-oss-request-id"]);
      },
      headers: headers,
      copyheaders: copyheaders,
    });
    console.log(r2);

    // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject3.txt.
    const r3 = await client.multipartUploadCopy("destexampleobject3.txt", {
      // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
      sourceKey: "srcexampleobject.txt",
      // Specify the name of the source bucket. Example: sourcebucket.
      sourceBucketName: "sourcebucket",
    }, {
      checkpoint: savedCpt,
      progress: function (p, cpt, res) {
        console.log(p);
        console.log(cpt);
        console.log(res.headers["x-oss-request-id"]);
      },
    });
    console.log(r3);
  } catch (e) {
    console.log(e);
  }
}

copyLargeObjectBetweenDifferentBuckets()

Referencias

  • Copiar un objeto pequeño

    • Para consultar el código de ejemplo completo que permite copiar un objeto pequeño, revise el ejemplo de GitHub.

    • Para obtener más información sobre la operación de API que permite copiar un objeto pequeño, consulte CopyObject.

  • Copiar un objeto grande

    • Para consultar el código de ejemplo completo que permite copiar un objeto grande, revise el ejemplo de GitHub.

    • Para obtener más información sobre la operación de API que permite copiar un objeto grande, consulte UploadPartCopy.