OSS does not support renaming objects directly. To rename an object, perform a copy-then-delete operation: call CopyObject to create a new object with the desired name, then call DeleteObject to remove the source object.
Usage notes
-
In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see Regions and Endpoints.
-
This topic demonstrates creating an OSSClient instance with an OSS endpoint. For alternative configurations, such as using a custom domain or authenticating with credentials from Security Token Service (STS), see Create an OssClient.
Sample code
The following sample code shows how to rename an object named srcobject.txt to destobject.txt within examplebucket.
<?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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// The endpoint of the China (Hangzhou) region is used as an example. Specify the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name.
$bucket= "examplebucket";
// Specify the full path of the source object. The path cannot contain the bucket name. For example, srcobject.txt.
$fromObject = "srcobject.txt";
// Specify the full path of the destination object. The path cannot contain the bucket name. For example, destobject.txt.
$toObject = 'destobject.txt';
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Copy the srcobject.txt object to destobject.txt in the same bucket.
$ossClient->copyObject($bucket, $fromObject,$bucket, $toObject);
// Delete srcobject.txt.
$ossClient->deleteObject($bucket, $fromObject);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
print("Object ".$fromObject ." Rename complete" . PHP_EOL);
Renaming directories also requires this copy-then-delete approach. To rename a directory, you must recursively apply this operation to all objects and subdirectories within it.
References
For more information about the API operations for renaming an object, see CopyObject and DeleteObject.