Copie objetos dentro de un mismo bucket o entre buckets de la misma región.
Notas
Si utiliza herramientas de empaquetado como Webpack y Browserify, instale el SDK de OSS para Browser.js con el comando npm install ali-oss.
-
En la mayoría de los casos, el SDK de OSS para Browser.js se usa en navegadores. Para evitar que su par de AccessKey quede expuesto, se recomienda utilizar credenciales de acceso temporales obtenidas de Security Token Service (STS) para acceder a OSS.
Las credenciales de acceso temporales constan de un par de AccessKey y un token de seguridad. El par de AccessKey incluye un AccessKey ID y un AccessKey secret. Para obtener más información sobre cómo conseguir credenciales de acceso temporales, consulte Use STS for temporary access authorization.
Los buckets de origen y destino de la operación de copia deben tener configuradas reglas de intercambio de recursos de origen cruzado (CORS). Para obtener más información, consulte Preparations.
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 por defecto. La cuenta de Alibaba Cloud o el administrador de la cuenta debe otorgar los permisos de operación mediante RAM policies 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 si copia 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 si, al copiar un objeto, los metadatos del objeto de destino contienen X-Oss-Server-Side-Encryption: KMS. |
|
|
|
Copiar un objeto dentro de un bucket
A continuación se muestra cómo copiar el objeto srcobject.txt a destobject.txt dentro del bucket examplebucket.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id='upload'>Upload</button>
<button id='copy'>Copy</button>
<!--Import the SDK file.-->
<script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
<script type="text/javascript">
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from STS.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. Example: examplebucket.
bucket: "examplebucket",
});
const upload = document.getElementById('upload')
const copy = document.getElementById('copy')
// Specify the content of the object to upload.
const file = new Blob(['examplecontent'])
// Specify the full path of the object to upload. Example: srcobject.txt.
const fileName = 'srcobject.txt'
// Upload the object.
upload.addEventListener('click', () => {
const result = client.put(fileName, file).then(r => console.log(r))
})
// Copy the object.
copy.addEventListener('click', () => {
// Specify the name of the destination object.
client.copy('destobject.txt', fileName
// Set the HTTP headers and custom metadata for the destination object.
//{
// Specify the headers parameter to set the HTTP headers for the destination object. If you do not specify this parameter, the destination object has the same HTTP headers as the source object.
// headers:{
//'Cache-Control': 'no-cache',
// The copy operation is performed only if the ETag of the source object matches the specified ETag.
//'if-match': '5B3C1A2E053D763E1B002CC607C5****',
// The copy operation is performed only if the ETag of the source object does not match the specified ETag.
//'if-none-match': '5B3C1A2E053D763E1B002CC607C5****',
// The copy operation is performed only if the source object has been modified since the specified time.
//'if-modified-since': '2021-12-09T07:01:56.000Z',
// The copy operation is performed only if the source object has not been modified since the specified time.
//'if-unmodified-since': '2021-12-09T07:01:56.000Z',
// Specify the access control list (ACL) for the destination object. In this example, the ACL is set to private. This means only the object owner and authorized users have read and write permissions. Other users cannot access the object.
//'x-oss-object-acl': 'private',
// Specify the tags for the object. You can specify multiple tags.
//'x-oss-tagging': 'Tag1=1&Tag2=2',
// Specify whether to overwrite a destination object that has the same name. In this example, the value is set to true to prevent overwriting.
//'x-oss-forbid-overwrite': 'true',
//},
// Specify the meta parameter to customize the metadata of the destination object. If you do not specify this parameter, the destination object has the same metadata as the source object.
// meta:{
// location: 'hangzhou',
// year: 2015,
// people: 'mary'
//}
// }
).then(r => {
console.log(r.res.status)
})
})
</script>
</body>
</html>
Copiar un objeto entre buckets
A continuación se muestra cómo copiar el objeto srcobject.txt del bucket de origen srcbucket al objeto destobject.txt del bucket de destino destbucket.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="copy">Copy</button>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: "yourRegion",
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from STS.
accessKeyId: "yourAccessKeyId",
accessKeySecret: "yourAccessKeySecret",
// The security token obtained from STS.
stsToken: "yourSecurityToken",
// Specify the destination bucket name.
bucket: "destbucket",
});
const copy = document.getElementById("copy");
copy.addEventListener("click", () => {
client
.copy(
// Specify the name of the destination object.
"srcobject.txt",
// Specify the name of the source object.
"destobject.txt",
// Specify the source bucket name.
"srcbucket"
)
.then((r) => console.log(r));
});
</script>
</body>
</html>
Referencias
Para consultar el código de ejemplo completo sobre cómo copiar un objeto, visite ejemplos en GitHub.
Para obtener más información sobre la operación de API que permite copiar un objeto, consulte CopyObject.