All Products
Search
Document Center

Object Storage Service:Rename objects

Last Updated:Aug 20, 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.

Usage notes

  • Before you run the sample code in this topic, you must create an OSSClient instance by using methods such as using a custom domain name or Security Token Service (STS). For more information, see Initialization.

    Note

    The region of the bucket is determined by the endpoint specified for initialization.

Sample code

The following code provides an example on how to rename an object named srcobject.txt in the examplebucket bucket to destobject.txt:

// 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;
}];
Note

Directories also cannot be directly renamed. To rename a directory, 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.