All Products
Search
Document Center

Object Storage Service:Rename objects in line with naming conventions

Last Updated:May 15, 2025

During OSS data migration or reorganization, you can rename files to ensure naming consistency and structural accuracy. After the hierarchical namespace feature is enabled for a bucket, you can directly rename objects in the bucket.

Scenarios

  • Naming convention implementation: When implementing new file naming conventions, you need to rename existing objects to improve data management efficiency and consistency.

  • Data migration and reorganization: During organizational structure adjustments, system migrations, or application upgrades, you may need to rename and reorganize data in OSS.

  • Storage layout optimization: To improve data retrieval performance and organizational structure, you sometimes need to rename objects to optimize storage layout and virtual directory structure.

Notes

  • If the hierarchical namespace feature is enabled for a bucket, you can call the Rename operation to rename objects in the bucket.

    For more information about the hierarchical namespace feature, see Use the hierarchical namespace feature.

  • If the hierarchical namespace feature is not enabled for a bucket, objects in the bucket cannot be directly renamed. To rename an object in the bucket, you can call the CopyObject operation to copy the source object to the destination object and call the DeleteObject operation to delete the source object.

Procedure

Use the OSS console

Important

The OSS console does not limit the size of objects that you can rename. However, the size of objects that you can move cannot exceed 1 GB.

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. Rename the object.

    • The hierarchical namespace feature is not enabled for the bucket

      In the left-side navigation pane, choose Object Management > Objects. Move the pointer over the target object, and then click the edit icon to rename the object. When you rename the object, make sure that the object name contains a file extension.

    • The hierarchical namespace feature is enabled for the bucket

      In the left-side navigation pane, choose Object Management > Objects, and then rename or move the object.

      Scenario

      Operation

      Rename an object

      Move the pointer over the target object, and then click the edit icon to rename the object. When you rename the object, make sure that the object name contains a file extension.

      Move an object

      Choose ActionsMore > Move Object from the Move Object column corresponding to the target object. On the page, specify the destination directory based on the following scenarios.

      • To move the object to the root directory of the current bucket, leave the destination directory blank.

      • To move the object to a specific directory in the current bucket, such as the subdirectory named subdir in the parent directory named destdir, set the destination directory to destdir/subdir.

Use Alibaba Cloud SDKs

The following sample code provides examples on how to rename srcobject.txt in the examplebucket bucket to destobject.txt:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.RenameObjectRequest;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked, which compromises the security of all resources in your account. This example obtains access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name.
        String bucketName = "examplebucket";
        // Specify the full path of the source object. The full path cannot contain the bucket name.
        String sourceObject = "srcobject.txt";
        // Specify the full path of the destination object. Do not include the bucket name in the full path.
        String destinationObject = "destobject.txt";

        // Create an OSSClient instance.
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // If the hierarchical namespace feature is enabled for the bucket, run the following code to rename the object.
            // Change the absolute path of the source object in the bucket to the absolute path of the destination object.
            RenameObjectRequest renameObjectRequest = new RenameObjectRequest(bucketName, sourceObject, destinationObject);
            ossClient.renameObject(renameObjectRequest);

            // If the hierarchical namespace feature is not enabled for the bucket, run the following code to rename the object:
            // Copy the srcobject.txt object in examplebucket to the destobject.txt object in the same bucket.
            // ossClient.copyObject(bucketName, sourceObject, bucketName, destinationObject);

            // Delete the srcobject.txt object.
            // ossClient.deleteObject(bucketName, sourceObject);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
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();
// Specify the name of the bucket. 
String bucketName = "examplebucket";
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcobject.txt. 
String sourceObjectKey = "srcobject.txt";
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destobject.txt. 
String objectKey = "destobject.txt";
try {
    CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucketName, sourceObjectKey, bucketName, objectKey);
    oss.copyObject(copyObjectRequest);
    // Delete the srcobject.txt object. 
    DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, sourceObjectKey);
    oss.deleteObject(deleteObjectRequest);
} catch (ClientException e) {
    // Handle client-side exceptions, such as network errors. 
    e.printStackTrace();
} catch (ServiceException e) {
    // Handle server-side exceptions. 
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}
// Specify the name of the bucket. 
NSString *bucketName = @"examplebucket";
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcobject.txt. 
NSString *sourceObjectKey = @"sourceObjectKey";
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destobject.txt. 
NSString *objectKey = @"destobject.txt";
[[[OSSTask taskWithResult:nil] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
    // Copy the srcobject.txt object to the destobject.txt object in the same bucket. 
    OSSCopyObjectRequest *copyRequest = [OSSCopyObjectRequest new];
    copyRequest.bucketName = bucketName;
    copyRequest.sourceBucketName = bucketName;
    copyRequest.sourceObjectKey = sourceObjectKey;
    copyRequest.objectKey = objectKey;
    OSSTask *copyTask = [client copyObject:copyRequest];
    [copyTask waitUntilFinished];
    if (copyTask.error) {
        return copyTask;
    }
    // Delete the srcobject.txt object. 
    OSSDeleteObjectRequest *deleteObject = [OSSDeleteObjectRequest new];
    deleteObject.bucketName = bucketName;
    deleteObject.objectKey = sourceObjectKey;
    OSSTask *deleteTask = [client deleteObject:deleteObject];
    [deleteTask waitUntilFinished];
    if (deleteTask.error) {
        return deleteTask;
    }
    return nil;
}] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
    if (task.error) {
        NSLog(@"rename fail! error: %@", task.error);
    } else {
        NSLog(@"rename success!");
    }
    return nil;
}];
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser
parser = argparse.ArgumentParser(description="copy object sample")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the destination bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint that other services can use to access OSS. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the destination object. This parameter is required.
parser.add_argument('--key', help='The name of the destination object.', required=True)
# Specify the --source_key parameter to indicate the name of the source object. This parameter is required.
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# Specify the --source_bucket parameter to indicate the name of the source bucket. This parameter is required.
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)

def main():
    # Parse the command line parameters
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configuration of the SDK and specify the credential provider
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located
    cfg.region = args.region

    # If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance
    client = oss.Client(cfg)

    # Copy the source object
    result = client.copy_object(oss.CopyObjectRequest(
        bucket=args.bucket,           # Specify the name of the destination bucket.
        key=args.key,  # Specify the key of the destination object.
        source_key=args.source_key,  # Specify the key of the source object.
        source_bucket=args.source_bucket,  # Specify the name of the source bucket.
    ))

    # Display the details of the operation result
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' hash crc64: {result.hash_crc64},'
          f' source version id: {result.source_version_id},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' last modified: {result.last_modified},'
          f' etag: {result.etag},'
    )

# Call the main function when the script is directly run
if __name__ == "__main__":
    main()  # Script entry point, calls the main function when the file is directly run
<?php

// Include the autoload file so that the required dependencies can be loaded
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the destination bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the destination object.
    "src-bucket" => ['help' => 'The name of the source bucket', 'required' => False], // (Optional) Specify the name of the source bucket.
    "src-key" => ['help' => 'The name of the source object', 'required' => True], // (Required) Specify the name of the source object.
];

// Convert the descriptions to a list of long options required by getopt
// Add a colon (:) to the end of each parameter to indicate that a value is required
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters
$options = getopt("", $longopts);

// Check whether the required parameters are missing
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the parameter
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing
    }
}

// Extract parsed arguments and use them
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the destination bucket
$key = $options["key"];       // The name of the destination object
$srcKey = $options["src-key"]; // The name of the source object

// Obtain access credentials from environment variables
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, specify the endpoint
}

// Create an OSSClient instance
$client = new Oss\Client($cfg);

// Create a CopyObjectRequest object to copy the source object
$request = new Oss\Models\CopyObjectRequest(
            bucket: $bucket,
            key: $key,
            sourceKey: $srcKey,
            sourceBucket: $bucket);

if (!empty($options["src-bucket"])) {
    $request->sourceBucket = $options["src-bucket"]; // If the source bucket name is provided, set sourceBucket
}
$request->sourceKey = $srcKey; // Set the name of the source object

// Perform the object copy operation
$result = $client->copyObject($request);

// Display the object copy result
printf(
    'status code:' . $result->statusCode . PHP_EOL . // HTTP status code, such as 200 for success
    'request id:' . $result->requestId . PHP_EOL     // Request ID for debugging or tracking requests
);

For code examples on how to rename objects by using other SDKs, see SDK overview.

Use ossbrowser

Operations supported by ossbrowser at the bucket level are similar to those supported by the OSS console. Follow the ossbrowser interface to rename files. For more information about how to use ossbrowser, see Common operations.

Use ossutil

For example, to rename examplefile.txt in the examplebucket1 bucket to example.txt, run the following commands:

ossutil cp oss://examplebucket1/examplefile.txt oss://examplebucket1/example.txt 
ossutil rm oss://examplebucket1/examplefile.txt

For more information about how to use ossutil to rename objects, see cp (copy objects) and rm (delete).

Use REST API

If your program requires more custom options, you can directly call RESTful API operations. To directly call an API operation, you must include the signature calculation in your code. For more information, see Rename.

References