OSS does not provide a native rename operation. To rename an object, copy it to a new key within the same bucket by calling CopyObject, then delete the original by calling DeleteObject.
How it works
A rename operation consists of two sequential API calls:
CopyObject -- Copy the source object to the destination key in the same bucket.
DeleteObject -- Delete the source object after the copy succeeds.
The sample code below checks for errors after each step. If the copy fails, the source object remains unchanged. If the copy succeeds but the delete fails, both the source and destination objects exist in the bucket.
Prerequisites
Before you begin, make sure that you have:
An OSSClient instance initialized with a custom domain name or Security Token Service (STS). For more information, see Initialization (iOS SDK)
The bucket region is determined by the endpoint specified in the initialization configuration.
Sample code
The following Objective-C example renames srcobject.txt to destobject.txt in the examplebucket bucket.
// Specify the bucket name.
NSString *bucketName = @"examplebucket";
// Specify the full path of the source object. Do not include the bucket name.
NSString *sourceObjectKey = @"srcobject.txt";
// Specify the full path of the destination object. Do not include the bucket name.
NSString *objectKey = @"destobject.txt";
[[[OSSTask taskWithResult:nil] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
// Copy srcobject.txt to destobject.txt 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 source 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;
}];Rename folders
OSS does not support renaming folders directly. To rename a folder, apply the same copy-then-delete method to each subdirectory and object within the folder.