Renommez des objets dans OSS pour appliquer des conventions de nommage ou réorganiser votre structure de données. Si l'espace de noms hiérarchique est activé pour un bucket, vous pouvez renommer les objets directement.
Cas d'utilisation
Appliquer des conventions de nommage : renommez les objets existants pour imposer une nouvelle norme de nommage dans l'ensemble de votre bucket.
Migrer et réorganiser les données : renommez les objets lors de migrations système, de mises à niveau d'applications ou de restructurations organisationnelles.
Optimiser la disposition du stockage : renommez les objets pour améliorer la structure de répertoires virtuelle, facilitant ainsi la récupération et l'organisation des données.
Notes d'utilisation
-
Si l'espace de noms hiérarchique est activé pour un bucket, appelez l'API
RenameObjectpour renommer directement les objets. Si l'espace de noms hiérarchique n'est pas activé, utilisez la méthode « copier puis supprimer » : appelez
CopyObjectpour copier l'objet sous un nouveau nom, puis appelezDeleteObjectpour supprimer l'original.
Procédure
Utiliser la console OSS
La console OSS n'impose aucune limite de taille pour le renommage des objets. Toutefois, les objets que vous déplacez ne peuvent pas dépasser 1 Go.
Connectez-vous à la console OSS.
Dans le volet de navigation de gauche, cliquez sur Buckets. Sur la page qui s'affiche, cliquez sur le nom du bucket cible.
-
Renommez l'objet.
-
Si l'espace de noms hiérarchique n'est pas activé pour le bucket
Dans le volet de navigation de gauche, choisissez Object Management > Objects. Survolez l'objet cible, cliquez sur l'icône

, puis renommez l'objet. Le nouveau nom d'objet doit inclure l'extension de fichier. -
Si l'espace de noms hiérarchique est activé pour le bucket
Dans le volet de navigation de gauche, choisissez Object Management > Objects. Ensuite, renommez ou déplacez l'objet.
Opération
Étape
Renommer un objet
Survolez l'objet cible et cliquez sur l'icône
pour renommer l'objet. Le nouveau nom d'objet doit inclure l'extension de fichier. Déplacer un objet
Dans la colonne Actions de l'objet cible, choisissez More > Move Object. Dans le panneau Move Object, saisissez le répertoire de destination en fonction de votre cas d'utilisation.
-
Pour déplacer l'objet vers le répertoire racine du bucket actuel, laissez le champ de répertoire de destination vide.
-
Pour déplacer l'objet vers un répertoire spécifique du bucket actuel, saisissez le chemin d'accès du répertoire. Par exemple, pour déplacer l'objet vers le répertoire « subdir » situé dans le répertoire « destdir », définissez le répertoire de destination sur destdir/subdir.
-
-
Utiliser les SDK OSS
Le code suivant renomme srcobject.txt en destobject.txt dans 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 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.
);
La référence du SDK inclut des exemples de renommage pour d'autres langages de programmation.
Utiliser ossbrowser
ossbrowser prend en charge des opérations au niveau du bucket similaires à celles de la console OSS. Suivez les instructions à l'écran pour renommer les objets. Pour plus d'informations, consultez Opérations courantes.
Utiliser ossutil
Les commandes suivantes renomment srcobject.txt en destobject.txt dans examplebucket :
ossutil cp oss://examplebucket/srcobject.txt oss://examplebucket/destobject.txt
ossutil rm oss://examplebucket/srcobject.txt
Pour plus d'informations sur le renommage des objets à l'aide des commandes ossutil, consultez cp et rm.
Utiliser l'API RESTful
Pour appeler directement les API RESTful, intégrez le calcul de signature dans votre code. Pour plus d'informations, consultez Rename.
Références
Lorsque vous téléchargez un objet, utilisez une URL pré-signée ou les métadonnées de l'objet pour spécifier le nom du fichier téléchargé. Cela permet d'éviter des coûts supplémentaires et de prévenir les erreurs dans les applications qui dépendent du nom de l'objet source. Pour plus d'informations, consultez Spécifier les noms des objets téléchargés.