All Products
Search
Document Center

Object Storage Service:Rename objects

Last Updated:Nov 05, 2024

Objects cannot be directly renamed. To rename an object in a bucket, you can call the CopyObject operation to copy the source object to the destination object and then call the DeleteObject operation to delete the source object.

Sample code

The following sample code provides examples on how to rename an object named srcobject.txt in examplebucket to destobject.txt:

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: 'oss-cn-hangzhou',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. 
  bucket: 'examplebucket',
})

async function renameObject() {
  try {
    // Copy the srcobject.txt object to the destobject.txt object in the same bucket. 
    const r = await client.copy('destobject.txt', 'srcobject.txt');
    console.log ('Copied', r);
    // Delete the srcobject.txt object. 
    const deleteResult = await client.delete('srcobject.txt');
    console.log(deleteResult);
  } catch (e) {
    console.log(e);
  }
}

renameObject();

Note

Directories in a bucket also cannot be directly renamed. To rename a directory in a bucket, you can follow the preceding example to rename the subdirectories and objects in the directory one by one.

References

For more information about the API operations that you can call to rename an object, see CopyObject and DeleteObject.