All Products
Search
Document Center

Object Storage Service:Rename objects

Last Updated:Sep 27, 2023

After you enable the hierarchical namespace feature for a bucket, you can rename objects in the bucket.

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 Enable hierarchical namespace.

  • If the hierarchical namespace feature is not enabled for a bucket, you cannot directly rename an object in the bucket. 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.

Use the OSS console

You can rename objects of all sizes in the OSS console. However, you can move only objects that do not exceed 1 GB in size in 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 and click the edit icon to rename the object. When you rename an object, the object name must contain a suffix.

    • The hierarchical namespace feature enabled for the bucket

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

      Scenario

      Procedure

      Rename an object

      Move the pointer over the object and click the edit icon to rename the object. When you rename an object, the object name must contain 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 specific 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 code provides examples on how to rename an object by using OSS SDKs for common programming languages. For more information about how to rename an object by using OSS SDKs for other programming languages, see Overview.

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. You need to configure environment variables before you run the sample code. 
        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 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();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the source object. The full path of the object cannot contain the bucket name. Example: srcobject.txt. 
$fromObject = "srcobject.txt";
// Specify the full path of the destination object. The full path of the object cannot contain the bucket name. Example: destobject.txt. 
$toObject = 'destobject.txt';

try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    // Copy the srcobject.txt object to the destobject.txt object in the same bucket. 
    $ossClient->copyObject($bucket, $fromObject,$bucket, $toObject);
    // Delete the srcobject.txt object. 
    $ossClient->deleteObject($bucket, $fromObject);
} catch (OssException $e) {
    printf($e->getMessage() . "\n");
    return;
}
print("Object ".$fromObject ." Rename complete" . PHP_EOL);
const OSS = require('ali-oss');
const client = new OSS({

  // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'oss-cn-hangzhou',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the name of the bucket. 
  bucket: 'examplebucket',
})
// Copy the srcobject.txt object to the destobject.txt object in the same bucket. 
client.copy('destobject.txt', 'srcobject.txt')
  .then(r => {
    console.log ('Copied', r);
    client
      // Delete the srcobject.txt object. 
      .delete('srcobject.txt')
      .then(r => console.log(r))
      .catch(e => console.log(e));
  })
  .catch(e => console.log(e));
# -*- 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 name of the bucket. Example: examplebucket. 
bucket_name = 'examplebucket'
# 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. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 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)

# Show the returned HTTP status code. 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)

# Show the returned HTTP status code. 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;
}];

Use ossutil

For more information about how to use ossutil to rename an object, see Copy objects.

Use RESTful APIs

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