During data migration or reorganization in Object Storage Service (OSS), you can rename objects to ensure consistent naming and an accurate directory structure. If Hierarchical Namespace is enabled for a bucket, you can rename objects in that bucket directly.
Use cases
Implement naming conventions: To enforce a new object naming convention, rename existing objects for better data management and consistency.
Migrate and reorganize data: Rename and reorganize data in OSS during organizational restructuring, system migrations, or application upgrades.
Optimize storage layout: Rename objects to optimize the storage layout and virtual directory structure, which improves data retrieval and organization.
Usage notes
If Hierarchical Namespace is enabled for a bucket, you can directly rename an object by calling the
RenameObjectAPI.For more information, see Use Hierarchical Namespace.
If Hierarchical Namespace is not enabled for a bucket, you cannot directly rename an object. In this scenario, you must perform a copy-then-delete operation: copy the source object to a destination object with the new name by using the
CopyObjectAPI, then delete the source object by using theDeleteObjectAPI.
Procedure
Use the OSS console
The OSS console does not limit the size of an object that you rename. However, the size of an object that you move cannot exceed 1 GB.
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
Rename the object.
If Hierarchical Namespace is not enabled for the bucket
In the left-side navigation pane, choose Object Management > Objects. Hover over the target object, click the
icon, then rename the object. The new object name must include the file extension.If Hierarchical Namespace is enabled for the bucket
In the left-side navigation pane, choose Object Management > Objects. Then, rename or move the object.
Operation
Step
Rename an object
Hover over the target object and click the
icon to rename the object. The new object name must include the file extension. Move an object
In the Actions column of the target object, choose More > Move Object. In the Move Object panel, enter the destination directory based on your use case.
To move the object to the root directory of the current bucket, leave the destination directory field empty.
To move the object to a specific directory in the current bucket, enter the path of the directory. For example, to move the object to the 'subdir' directory within the 'destdir' directory, set the destination directory to destdir/subdir.
Use OSS SDKs
The following sample code shows how to rename the object srcobject.txt to destobject.txt in examplebucket.
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";
// For security purposes, we recommend that you do not save access credentials in the project code. 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 Hierarchical Namespace is enabled for the bucket, use 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 Hierarchical Namespace is not enabled for the bucket, use 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,
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 argument parser
parser = argparse.ArgumentParser(description="copy object sample")
# Add command line argument --region, indicating the region where the bucket is located, required parameter
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add command line argument --bucket, indicating the name of the destination bucket, required parameter
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
# Add command line argument --endpoint, indicating the domain names that other services can use to access OSS, optional parameter
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add command line argument --key, indicating the name of the destination object, required parameter
parser.add_argument('--key', help='The name of the destination object.', required=True)
# Add command line argument --source_key, indicating the name of the source object, required parameter
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# Add command line argument --source_bucket, indicating the name of the source bucket, required parameter
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
def main():
# Parse command line arguments
args = parser.parse_args()
# Load credential information from environment variables for authentication
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and set the credential provider
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region information in the configuration
cfg.region = args.region
# If the endpoint parameter is provided, set the endpoint in the configuration
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client using the configured information
client = oss.Client(cfg)
# Execute the copy object request
result = client.copy_object(oss.CopyObjectRequest(
bucket=args.bucket, # Specify the name of the destination bucket
key=args.key, # Specify the key name of the destination object
source_key=args.source_key, # Specify the key name of the source object
source_bucket=args.source_bucket, # Specify the name of the source bucket
))
# Output the result information of the copy object
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},'
)
# When this script is run directly, call the main function
if __name__ == "__main__":
main() # Script entry point, call the main function when the file is run directlyFor code examples on how to rename an object using OSS SDKs for other programming languages, see SDK reference.
Use ossbrowser
ossbrowser supports bucket-level operations similar to those in the OSS console. Follow the on-screen instructions in ossbrowser to rename an object. For more information about how to use ossbrowser, see Common operations.
Use ossutil
Below are the sample commands for renaming examplefile.txt in examplebucket1 as example.txt:
ossutil cp oss://examplebucket/srcobject.txt oss://examplebucket/destobject.txt
ossutil rm oss://examplebucket/srcobject.txtFor more information about how to rename objects by using ossutil commands, see cp and rm.
Use the RESTful 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
When you download an object, use a presigned URL or object metadata to specify the name of the downloaded file to avoid extra costs and prevent errors in applications that depend on the source object name. For more information, see Specify names for downloaded objects.