OSS does not support renaming objects directly. To rename an object within the same bucket, copy it to a new key using CopyObject, then delete the original using DeleteObject.
How it works
Renaming an object involves two steps:
Copy the source object to the destination key within the same bucket.
Delete the source object.
To rename a directory, apply this copy-then-delete sequence recursively to every object and subdirectory it contains.
Rename an object
The following example renames srcobject.txt to destobject.txt in examplebucket.
const OSS = require('ali-oss');
const client = new OSS({
// Set the region where the bucket is located. Example: oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Load access credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this example.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket',
});
async function renameObject() {
try {
// Step 1: Copy srcobject.txt to destobject.txt.
const copyResult = await client.copy('destobject.txt', 'srcobject.txt');
console.log('Copied:', copyResult);
// Step 2: Delete the original object.
const deleteResult = await client.delete('srcobject.txt');
console.log('Deleted:', deleteResult);
} catch (e) {
console.error('Operation failed:', e.message || e);
}
}
renameObject();Replace the following placeholders with your actual values:
| Placeholder | Description | Example |
|---|---|---|
oss-cn-hangzhou | Region where the bucket is located | oss-cn-hangzhou |
examplebucket | Bucket name | examplebucket |
srcobject.txt | Key of the object to rename | logs/2024/app.log |
destobject.txt | New key for the renamed object | logs/2024/app-renamed.log |