You can rename objects in OSS to enforce naming conventions or reorganize your data structure during migrations.
Use cases
-
Implement naming conventions: Rename existing objects to enforce a new naming standard across your bucket.
-
Migrate and reorganize data: Rename objects during system migrations, application upgrades, or organizational restructuring.
-
Optimize storage layout: Rename objects to improve the virtual directory structure for better data retrieval and organization.
Usage notes
-
OSS does not support direct renaming. To rename an object, call CopyObject to copy the source object with a new name, then call DeleteObject to delete the source object.
-
Renaming an IA, Archive, Cold Archive, or Deep Cold Archive object stored for less than the minimum storage duration incurs charges for the remaining storage duration. For more information, see Storage fees.
-
In a versioning-enabled bucket, you can rename objects only when Previous Versions is set to Hide. Renaming creates a delete marker for the source object.
-
To rename multiple objects, list all source objects, copy them to destination objects with the new names, verify the destination objects, and then delete the source objects.
Procedure
Use the OSS console
The OSS console does not support renaming objects larger than 1 GB. To rename objects larger than 1 GB, use OSS SDKs, ossutil, or the RESTful API.
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
-
In the left-side navigation pane, choose Object Management > Objects. Hover over the target object and click the
icon to rename it. The new name must include the file extension.
Use OSS SDKs
The following code renames 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.ClientBuilderConfiguration;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.comm.SignVersion;
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称。
String bucketName = "examplebucket";
// 填写源Object的完整路径,完整路径中不能包含Bucket名称。
String sourceKey = "srcobject.txt";
// 填写目标Object的完整路径。Object完整路径中不能包含Bucket名称。
String destinationKey = "destobject.txt";
// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
String region = "cn-hangzhou";
// 创建OSSClient实例。
// 当OSSClient实例不再使用时,调用shutdown方法以释放资源。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 将examplebucket下的srcobject.txt拷贝至同一Bucket下的destobject.txt。
ossClient.copyObject(bucketName, sourceKey, bucketName, destinationKey);
// 删除srcobject.txt。
ossClient.deleteObject(bucketName, sourceKey);
} 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 running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket',
})
async function renameObject() {
try {
// Copy the source object 'srcobject.txt' to a new destination object 'destobject.txt'.
const r = await client.copy('destobject.txt', 'srcobject.txt');
console.log ('Copied', r);
// Delete srcobject.txt.
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 bucket name.
NSString *bucketName = @"examplebucket";
// Specify the full path of the source object. Do not include the bucket name. For example, srcobject.txt.
NSString *sourceObjectKey = @"sourceObjectKey";
// Specify the full path of the destination object. Do not include the bucket name. For example, destobject.txt.
NSString *objectKey = @"destobject.txt";
[[[OSSTask taskWithResult:nil] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
// Copy the srcobject.txt object 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 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 the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the destination bucket. This is a required parameter.
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the endpoint that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the destination object. This is a required parameter.
parser.add_argument('--key', help='The name of the destination object.', required=True)
# Add the --source_key command-line argument, which specifies the name of the source object. This is a required parameter.
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# Add the --source_bucket command-line argument, which specifies the name of the source bucket. This is a required parameter.
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If an endpoint is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client with the specified configurations.
client = oss.Client(cfg)
# Send a request to copy the object.
result = client.copy_object(oss.CopyObjectRequest(
bucket=args.bucket, # Specify the name of the destination bucket.
key=args.key, # Specify the key of the destination object.
source_key=args.source_key, # Specify the key of the source object.
source_bucket=args.source_bucket, # Specify the name of the source bucket.
))
# Delete the original object.
client.delete_object(oss.DeleteObjectRequest(
bucket=args.source_bucket,
key=args.source_key
))
# Print the result of the copy operation.
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},'
)
# Call the main function when the script is run directly.
if __name__ == "__main__":
main() # Script entry point. The main function is called when the file is run directly.<?php
// Import the autoloader file to ensure that the dependency libraries are loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the descriptions for command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. (Optional)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the destination bucket. (Required)
"key" => ['help' => 'The name of the object', 'required' => True], // The name of the destination object. (Required)
"src-bucket" => ['help' => 'The name of the source bucket', 'required' => False], // The name of the source bucket. (Optional)
"src-key" => ['help' => 'The name of the source object', 'required' => True], // The name of the source object. (Required)
];
// Convert the argument descriptions to the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command-line arguments.
$options = getopt("", $longopts);
// Verify that the required arguments are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information for the argument.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is missing, exit the program.
}
}
// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the destination bucket.
$key = $options["key"]; // The name of the destination object.
$srcKey = $options["src-key"]; // The name of the source object.
// Load credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a CopyObjectRequest object to copy an object.
$request = new Oss\Models\CopyObjectRequest(
bucket: $bucket,
key: $key,
sourceKey: $srcKey,
sourceBucket: $bucket);
if (!empty($options["src-bucket"])) {
$request->sourceBucket = $options["src-bucket"]; // If a source bucket name is provided, set sourceBucket.
}
$request->sourceKey = $srcKey; // Set the source object name.
// Execute the copy object operation.
$result = $client->copyObject($request);
// Print the copy result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
'request id:' . $result->requestId . PHP_EOL // The request ID, which is used for debugging or tracking requests.
);
The SDK reference includes rename examples for other programming languages.
Use ossbrowser
ossbrowser supports bucket-level operations similar to those in the OSS console. Follow the on-screen instructions to rename objects. ossbrowser 2.0 common operations.
Use ossutil
Use the RESTful API
To call RESTful APIs directly, include the signature calculation in your code. For more information, see CopyObject and DeleteObject.
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.