Todos os produtos
Search
Central de documentação

Object Storage Service:Rename objects

Última atualização: Sep 22, 2026

Você pode renomear objetos no OSS para aplicar convenções de nomenclatura ou reorganizar sua estrutura de dados. Se o Hierarchical Namespace estiver ativado para um bucket, você poderá renomear objetos diretamente.

Casos de uso

  • Implementar convenções de nomenclatura: Renomeie objetos existentes para aplicar um novo padrão de nomenclatura em todo o seu bucket.

  • Migrar e reorganizar dados: Renomeie objetos durante migrações de sistema, atualizações de aplicativos ou reestruturações organizacionais.

  • Otimizar o layout de armazenamento: Renomeie objetos para melhorar a estrutura de diretórios virtuais, facilitando a recuperação e a organização dos dados.

Notas de uso

  • Se o Hierarchical Namespace estiver ativado para um bucket, chame a API RenameObject para renomear objetos diretamente.

    Use Hierarchical Namespace.

  • Se o Hierarchical Namespace não estiver ativado, use o método de cópia e exclusão: chame CopyObject para copiar o objeto com um novo nome e, em seguida, chame DeleteObject para remover o original.

Procedimento

Usar o console do OSS

Importante

O console do OSS não impõe limite de tamanho para a renomeação de objetos. No entanto, os objetos movidos não podem exceder 1 GB.

  1. Acesse o console do OSS.

  2. No painel de navegação à esquerda, clique em Buckets. Na página exibida, clique no nome do bucket de destino.

  3. Renomeie o objeto.

    • Se o Hierarchical Namespace não estiver ativado para o bucket

      No painel de navegação à esquerda, escolha Object Management > Objects. Passe o mouse sobre o objeto de destino, clique no ícone edit e renomeie o objeto. O novo nome do objeto deve incluir a extensão do arquivo.

    • Se o Hierarchical Namespace estiver ativado para o bucket

      No painel de navegação à esquerda, escolha Object Management > Objects. Em seguida, renomeie ou mova o objeto.

      Operação

      Etapa

      Renomear um objeto

      Passe o mouse sobre o objeto de destino e clique no ícone edit para renomear o objeto. O novo nome do objeto deve incluir a extensão do arquivo.

      Mover um objeto

      Na coluna Actions do objeto de destino, escolha More > Move Object. No painel Move Object, insira o diretório de destino com base no seu caso de uso.

      • Para mover o objeto para o diretório raiz do bucket atual, deixe o campo do diretório de destino vazio.

      • Para mover o objeto para um diretório específico no bucket atual, insira o caminho do diretório. Por exemplo, para mover o objeto para o diretório 'subdir' dentro do diretório 'destdir', defina o diretório de destino como destdir/subdir.

Usar os SDKs do OSS

O código a seguir renomeia srcobject.txt para destobject.txt em 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.
);

O SDK reference inclui exemplos de renomeação para outras linguagens de programação.

Usar o ossbrowser

O ossbrowser permite operações no nível do bucket semelhantes às do console do OSS. Siga as instruções na tela para renomear objetos. Para mais informações, consulte 常用操作.

Usar o ossutil

Os comandos a seguir renomeiam srcobject.txt para destobject.txt em examplebucket:

ossutil cp oss://examplebucket/srcobject.txt oss://examplebucket/destobject.txt
ossutil rm oss://examplebucket/srcobject.txt

Para mais informações sobre como renomear objetos com comandos do ossutil, consulte cp e rm.

Usar a API RESTful

Para chamar diretamente as APIs RESTful, inclua o cálculo de assinatura no seu código. Para mais informações, consulte Rename.

Referências

  • Ao baixar um objeto, use uma URL pré-assinada ou os metadados do objeto para especificar o nome do arquivo baixado. Isso evita custos extras e erros em aplicativos que dependem do nome do objeto source. Para mais informações, consulte Specify names for downloaded objects.

  • Rename a directory