OSS does not support renaming objects directly. To rename an object in the same bucket, call the CopyObject operation to copy the source object to a destination object. Then, call the DeleteObject operation to delete the source object.
Usage notes
When you use packaging tools such as Webpack and Browserify, install OSS SDK for Browser.js by running the npm install ali-oss command.
If you want to access an OSS bucket from a browser but no CORS rules are configured for the bucket, the browser rejects the request. Therefore, you must configure CORS rules for a bucket if you want to access the bucket from a browser. For more information, see Installation.
In most cases, OSS SDK for Browser.js is used in browsers. To prevent your AccessKey pair from being exposed, we recommend that you use temporary access credentials obtained from Security Token Service (STS) to access OSS.
The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information about how to obtain temporary access credentials, see Use STS for temporary access authorization.
Sample code
The following code shows how to rename the srcobject.txt object in the examplebucket bucket to destobject.txt.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id='rename'>Rename</button>
<!--Import the SDK file.-->
<script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js"></script>
<script type="text/javascript">
const client = new OSS({
// Set yourRegion to 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 Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. Example: examplebucket.
bucket: 'examplebucket',
});
// Rename srcobject.txt to destobject.txt in the same bucket.
const rename = async () => {
try {
// Step 1: Copy srcobject.txt to destobject.txt.
const copyResult = await client.copy('destobject.txt', 'srcobject.txt');
if (copyResult.res.status === 200) {
// Step 2: Delete the source object srcobject.txt.
await client.delete('srcobject.txt');
console.log('Object renamed from srcobject.txt to destobject.txt.');
}
} catch (err) {
console.error('Failed to rename object:', err);
}
};
document.getElementById('rename').addEventListener('click', rename);
</script>
</body>
</html>
References
For more information about the API operations for renaming files, see CopyObject and DeleteObject.