All Products
Search
Document Center

Object Storage Service:Rename objects based on naming conventions

Last Updated:Feb 01, 2024

During Object Storage Service (OSS) data migration or reorganization, you can rename objects based on new directory standards to ensure naming consistency and structure accuracy. Once you enable the hierarchical namespace feature for a bucket, you can rename objects in the bucket. This topic describes how to rename objects.

Scenarios

  • Naming convention enforcement: To implement new object naming conventions for higher data management efficiency and consistency, you need to rename existing objects to align with these conventions.

  • Data migration and reorganization: In the case of directory structure adjustment, system migration, or application upgrade, you may need to move or reorganize data stored in OSS, which means the objects may also need to be renamed.

  • Storage layout optimization: It is sometimes necessary to rename objects to accelerate data retrieval and optimize the storage directory structure.

Usage 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, see Use hierarchical namespace.

  • 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.

  • To maintain OSS-HDFS stability and prevent data loss, do not rename the .dlsdata/ directory of a bucket for which hierarchical namespace and OSS-HDFS are enabled.

Procedure

Use the OSS console

You can rename objects of any size, but can move only objects that are no more than 1 GB by using the OSS console.

  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 not enabled for the bucket

      In the left-side navigation tree, choose Object Management > Objects. Move the pointer over the object that you want to rename and click the edit icon to rename the object. When you rename an object, make sure that the object name contains a suffix.

    • The hierarchical namespace feature is enabled for the bucket

      In the left-side navigation tree, choose Object Management > Objects. Then, rename or move the object.

      Operation

      Description

      Rename an object

      Move the pointer over the object that you want to rename and click the edit icon to rename the object. When you rename an object, make sure that the object name contains a suffix.

      Move an object

      In the Actions column of the object that you want to move, choose More > Move Object. In the Move Object panel, specify the destination directory to which you want to move the object.

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

      • To move the object to a directory in the current bucket, specify the directory as the destination directory. For example, to move the object to a subdirectory named subdir in a directory named destdir, set the destination directory to destdir/subdir.

Use OSS 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. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 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. 
        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 sample 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 the examplebucket bucket 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,
  // 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();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the name of the bucket. Example: examplebucket. 
bucket_name = 'examplebucket'
bucket = oss2.Bucket(auth, endpoint, bucket_name)

# Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcobject.txt. 
src_object_name = 'srcobject.txt'
# Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destobject.txt. 
dest_object_name = 'destobject.txt'

# Copy the srcobject.txt object in examplebucket to the destobject.txt object in the same bucket. 
result = bucket.copy_object(bucket_name, src_object_name, dest_object_name)

# View the response. If HTTP status code 200 is returned, the operation is successful. 
print('result.status:', result.status)

# Delete the srcobject.txt object. 
result_del = bucket.delete_object(src_object_name)

# View the response. If HTTP status code 204 is returned, the operation is successful. 
print('result.status:', result_del.status)
// Specify the bucket name. 
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());
}
package main

import (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)
func handleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}
func main()  {
    /// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        handleError(err)
    }
    // Specify the name of the bucket. 
    bucket, err := client.Bucket("examplebucket")
    if err != nil {
        handleError(err)
    }
    // Specify the full path of the source object. Do not include the bucket name in the full path. 
    srcObject := "srcobject.txt"
    // Specify the full path of the destination object. Do not include the bucket name in the full path. 
    destObject := "destobject.txt"
    // Copy the srcobject.txt object in examplebucket to the destobject.txt object in the same bucket. 
    _,err = bucket.CopyObject(srcObject,destObject)
    if err != nil {
        handleError(err)
    }
    // Delete the srcobject.txt object. 
    err = bucket.DeleteObject(srcObject)
    if err != nil {
        handleError(err)
    }

    fmt.Print(srcObject+" has renamed "+destObject)
}
// Specify the bucket name. 
NSString *bucketName = @"examplebucket";
// Specify the full path of the source object. The full path of the object cannot contain the bucket name. Example: srcobject.txt. 
NSString *sourceObjectKey = @"sourceObjectKey";
// Specify the full path of the destination object. The full path of the object cannot contain the bucket name. Example: destobject.txt. 
NSString *objectKey = @"destobject.txt";
[[[OSSTask taskWithResult:nil] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
    // Copy the srcobject.txt object in examplebucket 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;
}];

For more information about how to rename an object by using OSS SDKs for other programming languages, see Overview.

Use the OSS API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see Rename.

References

  • If you want to rename an object when you download it, we recommend that you use a pre-signed URL or object metadata instead of renaming the object directly. If you rename objects by using copy and delete operations, you are charged additional fees and errors may occur in applications that rely on the source object names. For more information, see Specify names for downloaded objects.

  • For more information about how to rename a directory, see Rename a directory.