Ao ativar o versionamento em um bucket, o OSS atribui um ID exclusivo a cada versão do objeto. Os objetos existentes mantêm seu conteúdo e ACL. O versionamento evita substituições ou exclusões acidentais e permite consultar ou restaurar versões anteriores.
Observações de uso
Ao fazer upload, listar, baixar, excluir ou restaurar objetos em um bucket com versionamento ativado:
O OSS mantém uma versão atual e zero ou mais versões anteriores para cada objeto.
Objetos existentes no bucket antes da ativação do versionamento recebem o ID de versão null.
Para maior clareza, os IDs de versão nas figuras deste tópico estão simplificados.
Uma regra de ciclo de vida que altera a classe de armazenamento de um objeto não cria uma nova versão.
Fazer upload de objetos
Ao fazer upload de um objeto para um bucket com versionamento ativado, o OSS atribui a ele um ID de versão exclusivo.
As operações PutObject, PostObject, CopyObject e MultipartUpload atribuem, cada uma, um ID de versão exclusivo ao objeto recém-criado.
Ao executar PUT em um objeto, o OSS atribui a ele um ID de versão exclusivo (por exemplo, 111111).
Ao executar PUT em um objeto com o mesmo nome (key=example.jpg), a versão existente (ID=111111) torna-se uma versão anterior e a nova versão (ID=222222) passa a ser a atual. Fazer upload da mesma chave novamente transforma os IDs 111111 e 222222 em versões anteriores, enquanto o ID=333333 se torna a versão atual.

Usar o console do OSS
Faça logon no console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.
No painel de navegação à esquerda, escolha Object Management > Objects.
Na página Objects, clique em Upload Object.
-
No painel Upload Object, configure os seguintes parâmetros.
-
Configure as opções básicas.
<!--@div {"id":"info_sgx_gt4_4wz","data-tag="info"}-->
Parâmetro
Descrição
Upload To
Especifique o caminho de armazenamento do objeto.
-
Current Directory: Faz o upload do objeto para o diretório atual.
-
Specified Directory: Faz o upload do objeto para um diretório específico. Insira um nome de diretório. Caso o diretório não exista, o OSS o cria automaticamente e faz o upload do objeto nele.
O nome do diretório deve atender aos seguintes requisitos:
-
Deve ter entre 1 e 254 caracteres e estar codificado em UTF-8.
-
Não pode começar com barra (/) ou barra invertida (\).
-
Não pode conter barras consecutivas (/).
-
Não pode consistir em dois pontos consecutivos (
..).
-
Object ACL
Defina a lista de controle de acesso (ACL) do objeto.
-
Inherited from Bucket: O objeto herda a ACL do bucket.
-
Private (Recomendado): Apenas o proprietário do objeto tem permissões de leitura e gravação. Outros usuários não podem acessar o objeto.
-
Public Read: O proprietário tem permissões de leitura e gravação. Outros usuários, incluindo anônimos, têm apenas permissão de leitura. Essa configuração pode causar vazamento de dados e custos inesperadamente altos. Proceda com cautela.
-
Public Read/Write: Todos os usuários, inclusive anônimos, podem ler e gravar no objeto. Essa configuração representa um risco significativo de segurança, pois usuários mal-intencionados podem gravar conteúdo não autorizado. Evite conceder permissões públicas de leitura/gravação, a menos que seja absolutamente necessário.
Files to Upload
Selecione os arquivos ou pastas para upload.
Clique em Select Files ou Select Folders para selecionar arquivos ou pastas locais. Também é possível arrastar os arquivos ou pastas para a área Files to Upload.
Se uma pasta selecionada contiver arquivos indesejados, localize-os na lista e clique em Remove na coluna Actions.
Importante-
Ao fazer upload de um objeto com o mesmo nome de um objeto existente em um bucket sem versionamento, o objeto existente será substituído.
-
Ao fazer upload de um objeto com o mesmo nome de um objeto existente em um bucket com versionamento ativado, o novo objeto torna-se a versão atual e o objeto existente passa a ser uma versão anterior.
-
-
Opcional: Clique no ícone
à direita de Advanced Settings para configurar opções avançadas, como Storage Class e Server-side Encryption.<!--@div {"id":"info_4pc_gxa_pwj","data-tag="info"}-->
Parâmetro
Descrição
Storage Class
Defina a classe de armazenamento do objeto. Valores válidos:
-
Inherited from Bucket (Padrão): O objeto herda a classe de armazenamento do bucket.
-
Standard: Oferece armazenamento de objetos confiável, altamente disponível e de alto desempenho para dados acessados frequentemente. Adequado para diversos cenários, como aplicativos sociais e de compartilhamento de imagens, áudio e vídeo, grandes sites e análise de big data. A classe Standard suporta armazenamento redundante por zona (ZRS) e armazenamento localmente redundante (LRS).
-
IA: Fornece um serviço de armazenamento de objetos altamente durável com custo reduzido. Possui tamanho mínimo faturável de 64 KB e período mínimo de armazenamento de 30 dias. Os dados são acessíveis em tempo real, mas há taxas de recuperação. Ideal para cenários de baixa frequência de acesso, como uma ou duas vezes por mês. Suporta ZRS e LRS.
-
Archive: Oferece armazenamento altamente durável a um custo extremamente baixo. Tamanho mínimo faturável de 64 KB e período mínimo de 60 dias. O acesso requer restauração prévia (cerca de um minuto) ou acesso direto, ambos sujeitos a taxas. Recomendado para arquivamento de longo prazo, como imagens médicas, materiais científicos e vídeos. Suporta ZRS e LRS.
-
Cold Archive: Proporciona armazenamento altamente durável com custo inferior ao Archive. Tamanho mínimo faturável de 64 KB e período mínimo de 180 dias. Objetos Cold Archive exigem restauração antes do acesso, cujo tempo varia conforme o tamanho e o modo de restauração. Taxas de recuperação e requisição se aplicam. Indicado para retenção prolongada de dados frios, como conformidade regulatória, dados brutos de big data e IA, ativos de mídia e vídeos educacionais. Suporta apenas LRS.
-
Deep Cold Archive: Oferece armazenamento altamente durável com custo menor que o Cold Archive. Tamanho mínimo faturável de 64 KB e período mínimo de 180 dias. Requer restauração prévia para acesso, com tempo dependente do tamanho e modo. Sujeito a taxas de recuperação e requisição. Destinado a dados extremamente frios de longa duração, como dados brutos de IA/big data, ativos de mídia, arquivos regulatórios e substituição de fitas. Suporta apenas LRS.
Encryption Method
Defina o método de criptografia no lado do servidor para o objeto. Valores válidos:
-
Inherited from Bucket (Padrão): O objeto herda o método de criptografia no lado do servidor do bucket.
-
OSS-Managed: O OSS criptografa cada objeto com uma chave exclusiva gerenciada pelo próprio OSS. Para proteção adicional, essas chaves são criptografadas com uma chave mestra.
-
KMS: Utilize a chave mestra do cliente (CMK) padrão gerenciada pelo KMS ou uma CMK específica para criptografia e descriptografia.
Para usar a criptografia KMS, ative o serviço primeiro. Adquirir uma instância dedicada do KMS.
A seguir, a descrição do parâmetro CMK:
A chave de criptografia segue o formato
<alias>(CMK ID), onde<alias>é o alias da CMK e CMK ID é o identificador da CMK. Valores válidos:-
alias/acs/oss(CMK ID): Usa a CMK padrão gerenciada pelo KMS para gerar chaves diferentes e criptografar objetos distintos. A descriptografia ocorre automaticamente durante o download.
-
alias/<cmkname>(CMK ID): Esta opção utiliza uma CMK específica para gerar uma chave de criptografia única para cada objeto. O ID da CMK é armazenado nos metadados do objeto. Quando um usuário com as permissões necessárias baixa o objeto, o OSS o descriptografa automaticamente.
<cmkname>é o alias opcional da CMK definido durante sua criação.Antes de usar um ID de CMK específico, crie uma chave regular ou externa na mesma região do bucket no console do KMS. Para mais informações, consulte Criar uma CMK.
-
-
Encryption Algorithm: Apenas AES256 é suportado.
User-defined Metadata
Adicione informações descritivas ao objeto. É possível incluir múltiplas entradas de metadados definidos pelo usuário, desde que o tamanho total não exceda 8 KB. Cada chave de metadado deve ter o prefixo
x-oss-meta-e um valor atribuído. Exemplo: x-oss-meta-location:hangzhou. -
-
Clique em Upload Object.
<!--@div {"id":"stepresult_k2x_l9i_cj2","data-tag="stepresult"}-->
É possível acompanhar o progresso de upload de cada arquivo na aba Upload Tasks do painel Task List.
-
Usar SDKs da Alibaba Cloud
O código abaixo faz upload de um objeto para um bucket com versionamento ativado. Para outros SDKs, consulte Visão geral do SDK.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.io.ByteArrayInputStream;
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path.
String objectName = "exampledir/object";
// 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 cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// In this example, a string is uploaded as an object.
String content = "Hello OSS";
PutObjectResult result = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
// Display the version ID of the object.
System.out.println("result.versionid: " + result.getVersionId());
} 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: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
async function put() {
const result = await client.put('fileName', path.normalize('D:\\localpath\\examplefile.txt'));
console.log(result.res.headers['x-oss-version-id']); // Display the version ID of the uploaded object.
}
put();
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
var objectContent = "More than just cloud.";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
// Upload the object.
var result = client.PutObject(bucketName, objectName, requestContent);
Console.WriteLine("Put object succeeded versionid : {0}", result.VersionId);
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the Object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "test cpp sdk";
PutObjectRequest request(BucketName, ObjectName, content);
/* Upload the file. */
auto outcome = client.PutObject(request);
if (outcome.isSuccess()) {
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
package main
import (
"context"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Specify the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Define the init function used to initialize parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Specify the content that you want to upload.
content := "hi oss"
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to upload an object.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
Body: strings.NewReader(content), // The content that you want to upload.
}
// Execute the request to upload an object.
result, err := client.PutObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put object %v", err)
}
// Display the version ID of the object.
log.Printf("put object result versionId:%#v\n", *result.VersionId)
}
import argparse
import requests
import alibabacloud_oss_v2 as oss
# Create a command line argument parser.
parser = argparse.ArgumentParser(description="put object sample")
# Configure the --region command line argument to specify the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Configure the --bucket command line argument to specify the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Configure the --endpoint command line argument to specify the endpoint that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Configure the --key command line argument to specify the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
args = parser.parse_args() # Parse the command line arguments.
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Obtain the default configurations of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located.
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance.
client = oss.Client(cfg)
# Upload a local file.
local_file_path = '/yourLocalFilePath/yourFileName'
with open(local_file_path, 'rb') as file:
data = file.read()
# Execute the request to upload an object, and specify the bucket name, object name, and data content.
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=data,
))
# Display the HTTP status code in the response, the request ID, and the MD5 hash, ETag, CRC-64 value, and version ID of the object to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content md5: {result.content_md5},'
f' etag: {result.etag},'
f' hash crc64: {result.hash_crc64},'
f' version id: {result.version_id},'
)
if __name__ == "__main__":
main() # The entry point of the script. Call the main() function when the script is directly run.
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];
// Generate a list of long options to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Specify the data that you want to upload.
$data = 'Hello OSS';
// Create a simple upload request.
$request = new Oss\Models\PutObjectRequest(
bucket: $bucket,
key: $key,
);
// Set the request body to the data stream.
$request->body = Oss\Utils::streamFor($data);
// Use the putObject method to upload the data.
$result = $client->putObject($request);
// Display the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
'request id:' . $result->requestId . PHP_EOL . // The request ID.
'etag:' . $result->etag . PHP_EOL // The ETag of the object.
);
Usar ossutil
Para fazer upload de objetos em um bucket com versionamento ativado usando o ossutil, consulte cp (upload de objetos).
Usar uma API REST
Também é possível chamar a API REST diretamente. PutObject.
Listar objetos
Em um bucket com versionamento ativado, chame GetBucketVersions (ListObjectVersions) para recuperar informações sobre todas as versões dos objetos, incluindo marcadores de exclusão.
A operação GetBucket (ListObject) retorna apenas as versões atuais dos objetos que não são marcadores de exclusão.
-
Uma única requisição GetBucketVersions (ListObjectVersions) retorna até 1.000 versões de objetos. Para recuperar todas as versões, envie múltiplas requisições.
Por exemplo, se um bucket contiver duas chaves,
example.jpgephoto.jpg, ondeexample.jpgpossui 900 versões ephoto.jpgpossui 500 versões, uma única requisição listará todas as 900 versões deexample.jpge as primeiras 100 versões dephoto.jpg. Os resultados são ordenados pela chave em ordem lexicográfica e, em seguida, pela versão.
Conforme mostra a figura a seguir, GetBucketVersions (ListObjectVersions) retorna todas as versões, incluindo marcadores de exclusão. Já GetBucket (ListObject) retorna apenas as versões atuais que não são marcadores de exclusão, portanto, somente o objeto com ID de versão 444444 é retornado.

Console do OSS
Faça logon no console do OSS.
-
Clique em Buckets e, em seguida, clique no nome do bucket desejado.
Esta página exibe uma lista paginada da versão atual de cada objeto. Para visualizar todas as versões, incluindo marcadores de exclusão, acesse a página Objects e clique em Show ao lado de Previous Versions.
SDK do OSS
O código a seguir lista objetos em um bucket com versionamento ativado. Para outros SDKs, consulte Introdução ao SDK.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// 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 cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// List the versions of all objects, including delete markers in the bucket.
String nextKeyMarker = null;
String nextVersionMarker = null;
VersionListing versionListing = null;
do {
ListVersionsRequest listVersionsRequest = new ListVersionsRequest()
.withBucketName(bucketName)
.withKeyMarker(nextKeyMarker)
.withVersionIdMarker(nextVersionMarker);
versionListing = ossClient.listVersions(listVersionsRequest);
for (OSSVersionSummary ossVersion : versionListing.getVersionSummaries()) {
System.out.println("key name: " + ossVersion.getKey());
System.out.println("versionid: " + ossVersion.getVersionId());
System.out.println("Is latest: " + ossVersion.isLatest());
System.out.println("Is delete marker: " + ossVersion.isDeleteMarker());
}
nextKeyMarker = versionListing.getNextKeyMarker();
nextVersionMarker = versionListing.getNextVersionIdMarker();
} while (versionListing.isTruncated());
} 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({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before running this sample code, make sure 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: 'yourbucketname'
});
// List the version information of all objects, including delete markers.
async function getObjectVersions() {
let nextKeyMarker = null;
let nextVersionMarker = null;
let versionListing = null;
do {
versionListing = await client.getBucketVersions({
keyMarker: nextKeyMarker,
versionIdMarker: nextVersionMarker,
});
versionListing.objects.forEach((o) => {
console.log(`${o.name}, ${o.versionId}`);
});
versionListing.deleteMarker.forEach((o) => {
console.log(`${o.name}, ${o.versionId}`);
});
nextKeyMarker = versionListing.NextKeyMarker;
nextVersionMarker = versionListing.NextVersionIdMarker;
} while (versionListing.isTruncated);
}
getObjectVersions();
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="list object versions sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
# Parse the command-line arguments to obtain the specified values.
args = parser.parse_args()
# From the environment variables, load the authentication information required to access OSS.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration to create a cfg object and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding settings to initialize the OSSClient instance.
client = oss.Client(cfg)
# Create a Paginator object that is used to list object versions by page.
paginator = client.list_object_versions_paginator()
# Iterate over pages.
for page in paginator.iter_page(oss.ListObjectVersionsRequest(
bucket=args.bucket, # The bucket name.
)
):
# Iterate over object versions on the current page.
for o in page.version:
# Print the following information about each object version:
# - key: the object key.
# - size: the object size (bytes).
# - version_id: the version ID.
# - last_modified: the last modified time.
print(f'Object version: {o.key}, Size: {o.size}, Version_id: {o.version_id}, Last_modified: {o.last_modified}')
# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
main() # Specify the entry point of the script. The control flow starts here.
ossutil
Para listar objetos em um bucket com versionamento ativado usando o ossutil, consulte ls (Listar recursos no nível da conta).
API RESTful
Também é possível chamar a API REST diretamente. ListObjectVersions (GetBucketVersions).
Baixar objetos
É possível baixar a versão atual ou uma versão específica de um objeto.
Uma requisição GET sem um ID de versão retorna a versão atual (ID=333333).

Se a versão atual for um marcador de exclusão, a requisição GET retornará 404 Not Found.

Uma requisição GET com um ID de versão retorna essa versão específica (ID=222222).

Usar o console do OSS
Faça logon no console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.
No painel de navegação à esquerda, escolha Object Management > Objects.
Na página Objects, clique em Show à direita de Previous Versions.
Clique na versão do objeto que deseja baixar. No painel exibido, clique em Download à direita de Object URL.
Usar um SDK do OSS
O código a seguir baixa um objeto de um bucket com versionamento ativado. Para outros SDKs, consulte Visão geral do SDK.
const OSS = require('ali-oss');
const client = new OSS({
// Set yourregion to the region where the bucket is located. For example, for the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run this code, ensure that 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,
// Set yourbucketname to the name of the bucket.
bucket: 'yourbucketname'
});
async function get() {
// The name of the file.
const result = await client.get('filename', {
// The version ID of the file to download.
versionId: 'versionid',
});
console.log(result.content);
}
get();
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name, such as examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name, such as exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Download the file to the local memory. */
GetObjectRequest request(BucketName, ObjectName);
request.setVersionId("yourObjectVersionId");
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "getObjectToBuffer" << " success, Content-Length:" << outcome.result().Metadata().ContentLength() << std::endl;
/* Read the content of the downloaded object. */
std::string content;
*(outcome.result().Content()) >> content;
std::cout << "getObjectToBuffer" << "content:" << content << std::endl;
/* View the version ID of the downloaded object. */
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle the exception. */
std::cout << "getObjectToBuffer fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
import argparse
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser
parser = argparse.ArgumentParser(description="get object sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Specify the --version_id parameter, which specifies the version ID of the source object. This command line parameter is required.
parser.add_argument('--version_id', help='The version ID of the object.', required=True)
def main():
# Parse the command line parameters.
args = parser.parse_args()
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located.
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance.
client = oss.Client(cfg)
# Execute the request to download the object, and specify the bucket name and object name.
result = client.get_object(oss.GetObjectRequest(
bucket=args.bucket, # Specify the name of the bucket.
key=args.key, # Specify the name of the object.
version_id=args.version_id, # Specify the version ID.
))
# Display the response to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content length: {result.content_length},'
f' content range: {result.content_range},'
f' content type: {result.content_type},'
f' etag: {result.etag},'
f' last modified: {result.last_modified},'
f' content md5: {result.content_md5},'
f' cache control: {result.cache_control},'
f' content disposition: {result.content_disposition},'
f' content encoding: {result.content_encoding},'
f' expires: {result.expires},'
f' hash crc64: {result.hash_crc64},'
f' storage class: {result.storage_class},'
f' object type: {result.object_type},'
f' version id: {result.version_id},'
f' tagging count: {result.tagging_count},'
f' server side encryption: {result.server_side_encryption},'
f' server side data encryption: {result.server_side_data_encryption},'
f' next append position: {result.next_append_position},'
f' expiration: {result.expiration},'
f' restore: {result.restore},'
f' process status: {result.process_status},'
f' delete marker: {result.delete_marker},'
)
# Read the content of the object.
content = result.body.read()
# Save the content to a local file. In this example, the local file is named test.txt.
with open('./test.txt', 'wb') as f:
f.write(content)
print(f'File saved to test.txt successfully!')
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # Specify the entry points in the main function of the script when the script is directly run.
package main
import (
"context"
"flag"
"io"
"log"
"os"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region in which your bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the name of the object is specified.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Specify the path of the output file.
outputFile := "downloaded.file" // Replace this parameter with the path in which you want to save the file.
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a query request.
request := &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket
Key: oss.Ptr(objectName), // The name of the object
VersionId: oss.Ptr("yourVersionId"), // The version ID of the object
}
// Perform the query operation and process the result.
result, err := client.GetObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to get object %v", err)
}
defer result.Body.Close() // Make sure that the response body is closed when the function is complete.
// Read the entire file.
data, err := io.ReadAll(result.Body)
if err != nil {
log.Fatalf("failed to read object %v", err)
}
// Write the content to the file.
err = os.WriteFile(outputFile, data, 0644)
if err != nil {
log.Fatalf("failed to write to output file %v", err)
}
log.Printf("file downloaded successfully to %s", outputFile)
}
<?php
// Introduce autoload files to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];
// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain help information for the parameters.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // Exit the program if the required parameters are not configured.
}
}
// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.
// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
bucket: $bucket,
key: $key,
versionId:"yourVersionId",// Specify the version ID of the object.
);
// Query the object.
$result = $client->getObject($request);
// Specify the local path to save the object.
$localFilePath = './test/file.txt'; // Replace this parameter with the actual local file path.
// Write the content to the local file.
file_put_contents($localFilePath, $result->body->getContents());
// Display the result.
// Output the HTTP status code, request ID, and content of the object.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
);
Usar ossutil
Para baixar objetos de um bucket com versionamento ativado usando o ossutil, consulte cp (baixar objetos).
Usar uma API REST
Também é possível chamar a API REST diretamente. GetObject.
Excluir objetos
Em um bucket com versionamento ativado, é possível excluir permanentemente um objeto especificando seu ID de versão ou configurando uma regra de ciclo de vida. Se a exclusão for feita sem especificar um ID de versão, o OSS insere um marcador de exclusão como versão atual.
Após ativar o versionamento, excluir um objeto sem especificar um ID de versão não remove suas versões atuais ou não atuais por padrão.
Como lidar com um bucket que tem OSS-HDFS e versionamento ativados?.
Expiration: Aplica-se à versão atual de um objeto. Quando a versão atual expira, o OSS cria um marcador de exclusão e a versão expirada torna-se não atual.NoncurrentVersionExpiration: Aplica-se a versões não atuais de um objeto. Esta ação exclui permanentemente essas versões.
Para usar versionamento com regras de ciclo de vida, consulte Elementos de configuração de ciclo de vida.
A seguir, descrevemos o comportamento da operação DELETE com e sem um ID de versão especificado.
Se nenhum ID de versão for especificado, o OSS insere um marcador de exclusão como versão atual. O marcador de exclusão possui um ID de versão exclusivo, mas não contém dados nem ACL. Na figura abaixo, a versão atual é um marcador de exclusão com ID 444444.

Se um ID de versão for especificado, o OSS exclui permanentemente essa versão. Na figura abaixo, a versão com ID 333333 é excluída.

Console do OSS
Para minimizar custos de armazenamento, recomendamos excluir versões anteriores de objetos desnecessários o quanto antes.
Versões não atuais de objetos não podem ser restauradas após exclusão permanente. Proceda com cautela.
Faça logon no console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.
No painel de navegação à esquerda, escolha Object Management > Objects.
Na página Objects, clique em Show ao lado de Previous Versions.
-
Localize as versões não atuais desnecessárias e execute uma das seguintes ações:
Para excluir um marcador de exclusão, clique em Permanently Delete na coluna Actions.
Para excluir uma versão de objeto, passe o ponteiro sobre o ícone
na coluna Actions e clique em Permanently Delete.
Também é possível selecionar várias versões não atuais e clicar em Permanently Delete na parte inferior da página.
-
Clique em OK.
Alternativamente, configure uma regra de ciclo de vida para excluir periodicamente versões não atuais. Visão geral das regras de ciclo de vida.
SDK do OSS
O código a seguir exclui uma versão específica de um bucket com versionamento ativado. Para outros SDKs, consulte Visão geral do SDK.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path.
String objectName = "exampledir/object";
String versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
// 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 cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Delete the specified version of the object.
ossClient.deleteVersion(bucketName, objectName , versionId);
} 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({
// Replace yourregion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before running this sample code, make sure 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,
// Replace yourbucketname with the bucket name.
bucket: 'yourbucketname'
});
// Specify the versionId of the object.
const versionId = "versionId";
// Specify the object.
const objectName = "exampleobject.txt";
async function deleteVersionObject() {
const result = await client.delete(objectName, {
versionId,
});
console.log(result);
}
deleteVersionObject();
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the version ID of the object or the delete marker.
var versionid = "yourObjectVersionidOrDelMarkerVersionid";
// 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 cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Specify the version ID of the object or the delete marker that you want to delete.
var request = new DeleteObjectRequest(bucketName, objectName)
{
VersionId = versionid
};
client.DeleteObject(request);
Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete object failed. {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name, for example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Delete the object with the specified versionId or the object associated with the delete marker that has the specified versionId. */
auto outcome = client.DeleteObject(DeleteObjectRequest(BucketName, ObjectName, "yourObjectVersionIdOrDeleteMarkerVersionId"));
/* If the versionId of an object is specified, the returned delete_marker is None and the returned versionId is the versionId of the specified object. */
/* If the versionId of a delete marker is specified, the returned delete_marker is True and the returned versionId is the versionId of the specified delete marker. */
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "DeleteObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region where the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// init is used to initialize command-line flags.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command-line flags.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check if the object name is provided.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configuration and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to delete the object.
request := &oss.DeleteObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
VersionId: oss.Ptr("yourVersionId"), // Replace with the actual versionId of the object.
}
// Execute the delete operation and handle the result.
result, err := client.DeleteObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to delete object %v", err)
}
// Print the result.
log.Printf("delete object result:%#v\n", result)
}
<?php
// Import the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the description of command line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. This parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. This parameter is required.
"key" => ['help' => 'The name of the object', 'required' => True], // The object name. This parameter is required.
];
// Transform the argument descriptions into the long option format required by getopt.
// Add a colon (:) after each argument to indicate 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 all required arguments are specified.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information of the argument.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is missing, exit the program.
}
}
// Fetch values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"]; // The object name.
// 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 DeleteObjectRequest object to delete the specified object.
$request = new Oss\Models\DeleteObjectRequest(
bucket: $bucket,
key: $key,
versionId:"yourversionid", // Specify the version number of the object to be deleted.
);
// Execute the delete object operation.
$result = $client->deleteObject($request);
// Print the deletion result.
// Output the HTTP status code and request ID to verify whether the deletion is successful.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 204 indicates that the deletion is successful.
'request id:' . $result->requestId . PHP_EOL // The request ID, which is used to debug or track requests.
);
ossutil
Para excluir objetos de um bucket com versionamento ativado usando o ossutil, consulte rm (excluir).
API REST
Também é possível chamar a API REST diretamente. DeleteObject.
Restaurar objetos
Quando o versionamento está ativado, o OSS retém todas as versões dos objetos. É possível restaurar uma versão anterior para torná-la a versão atual.
Existem duas maneiras de restaurar uma versão anterior:
-
Copiar a versão anterior do objeto
A versão copiada torna-se a versão atual, e todas as versões existentes são mantidas.
Conforme mostra a figura, copiar uma versão anterior (ID=222222) para o mesmo bucket cria uma nova versão (ID=444444) como versão atual. A versão original (ID=222222) também é preservada.

-
Excluir permanentemente a versão atual do objeto
Como ilustra a figura a seguir, excluir permanentemente a versão atual (ID=222222) especificando seu ID de versão torna a próxima versão mais recente (ID=111111) a versão atual.

Uma versão excluída permanentemente não pode ser recuperada. Recomendamos restaurar versões anteriores copiando-as.
Usar o console do OSS
Faça logon no console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.
No painel de navegação à esquerda, escolha Object Management > Objects.
Na página Objects, clique em Show à direita de Previous Versions.
-
Restaure uma versão anterior de um objeto.
ImportanteÉ possível restaurar apenas uma versão de objeto por vez. Marcadores de exclusão não podem ser restaurados.
-
Para restaurar um único objeto
Na coluna Actions da versão desejada, clique em Restore.
-
Para restaurar vários objetos
Selecione as versões anteriores desejadas, clique em Restore na parte inferior da página e, em seguida, clique em OK na caixa de diálogo exibida.
-
Usar o SDK do OSS
O código a seguir copia uma versão específica em um bucket com versionamento ativado. Para outros SDKs, consulte Visão geral do SDK.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the source bucket.
String sourceBucketName = "srcexamplebucket";
// Specify the full path of the source object. Do not include the bucket name in the full path.
String sourceObjectName = "srcexampleobject.txt";
// Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket.
String destinationBucketName = "desexamplebucket";
// Specify the full path of the destination object. Do not include the bucket name in the full path.
String destinationObjectName = "desexampleobject.txt";
String versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
// 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 cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
copyObjectRequest.setSourceVersionId(versionId);
CopyObjectResult copyObjectResult = ossClient.copyObject(copyObjectRequest);
System.out.println("ETag: " + copyObjectResult.getETag() + " LastModified: " + copyObjectResult.getLastModified());
System.out.println("dest object versionid: " + copyObjectResult.getVersionId());
} 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({
// Set yourregion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before running this code sample, make sure 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,
// Set yourbucketname to the name of the bucket.
bucket: 'yourbucketname'
});
// Specify the versionId of the source object.
const versionId = 'versionId';
// Specify the source object.
const srcObject = 'srcObject.txt';
// Specify the source bucket.
const srcBucket = 'srcBucket';
// Specify the destination object.
const targetObject = 'targetObject.txt';
async function Copy() {
try {
const result = await client.copy(targetObject, srcObject, srcBucket, {
meta: {
versionId: versionId
}
});
console.log(result);
} catch (error) {
console.error(error);
}
}
Copy()
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the source bucket.
var sourceBucket = "yourSourceBucketName";
// Specify the full path of the source object. Do not include the bucket name in the full path.
var sourceObject = "yourSourceObjectName";
// Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket.
var targetBucket = "yourDestBucketName";
// Specify the full path of the destination object. Do not include the bucket name in the full path.
var targetObject = "yourDestObjectName";
// Specify the version ID of the source object.
var versionid = "yourArchiveObjectVersionid";
// 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 cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
var metadata = new ObjectMetadata();
metadata.AddHeader("mk1", "mv1");
metadata.AddHeader("mk2", "mv2");
var req = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject)
{
// If the value of NewObjectMetadata is null, the COPY mode is used and the metadata of the source object is copied to the destination object. If the value of NewObjectMetadata is not null, the REPLACE mode is used and the metadata of the source object overwrites the metadata of the destination object.
NewObjectMetadata = metadata,
// Specify the version ID of the object.
SourceVersionId = versionid
};
// Copy the object.
var result = client.CopyObject(req);
Console.WriteLine("Copy object succeeded, vesionid:{0}", result.VersionId);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2} \tHostID: {3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize OSS account information. */
/* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the name of the source bucket. Example: srcexamplebucket. */
std::string SourceBucketName = "srcexamplebucket";
/* Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket. */
std::string CopyBucketName = "destbucket";
/* Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt. */
std::string SourceObjectName = "srcdir/scrobject.txt";
/* Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt. */
std::string CopyObjectName = "destdir/destobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
CopyObjectRequest request(CopyBucketName, CopyObjectName);
request.setCopySource(SourceBucketName, SourceObjectName);
/* Specify the version ID of the source object. */
request.setVersionId("yourSourceObjectVersionId");
/* Copy the specified version of the object. */
auto outcome = client.CopyObject(request);
if (outcome.isSuccess()) {
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "CopyObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the object is stored.
srcBucketName string // Name of the source bucket.
srcObjectName string // Name of the source object.
destBucketName string // Name of the destination bucket.
destObjectName string // Name of the destination object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&srcBucketName, "src-bucket", "", "The name of the source bucket.")
flag.StringVar(&srcObjectName, "src-object", "", "The name of the source object.")
flag.StringVar(&destBucketName, "dest-bucket", "", "The name of the destination bucket.")
flag.StringVar(&destObjectName, "dest-object", "", "The name of the destination object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the source bucket is specified.
if len(srcBucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, source bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// If the name of the destination bucket is not specified, the name of the source bucket will be used.
if len(destBucketName) == 0 {
destBucketName = srcBucketName
}
// Check whether the name of the source object is specified.
if len(srcObjectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, source object name required")
}
// Check whether the name of the destination object is specified.
if len(destObjectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, destination object name required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a copy request.
copyRequest := &oss.CopyObjectRequest{
Bucket: oss.Ptr(destBucketName), // Name of the destination bucket.
Key: oss.Ptr(destObjectName), // Name of the destination object.
SourceKey: oss.Ptr(srcObjectName), // Name of the source object.
SourceBucket: oss.Ptr(srcBucketName), // Name of the source bucket.
SourceVersionId: oss.Ptr("yourVersionId"), // Specify the actual version ID of the source object.
StorageClass: oss.StorageClassStandard, // Set the storage class to Standard.
TaggingDirective: oss.Ptr("Replace"), // Tags of the source object are not copied.
Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the actual tags of the destination object.
}
// Perform the operation and process the result.
copyResult, err := client.CopyObject(context.TODO(), copyRequest)
if err != nil {
log.Fatalf("failed to copy object: %v", err)
}
// Display the result.
log.Printf("copy object result versionId:%#v\n", *copyResult.VersionId)
}
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the destination bucket.
"key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the destination object.
"src-bucket" => ['help' => 'The name of the source bucket', 'required' => False], // (Optional) Specify the name of the source bucket.
"key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the source object.
];
// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information about the parameters.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If the required parameters are not configured, exit the program.
}
}
// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the destination bucket.
$key = $options["key"]; // The name of destination object.
$srcKey = $options["src-key"]; // The name of the source object.
// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a CopyObjectRequest object to copy the source object.
$request = new Oss\Models\CopyObjectRequest(
bucket: $bucket,
key: $key,
sourceVersionId: "yourVersionId",// Specify the version ID of the source object.
);
if (!empty($options["src-bucket"])) {
$request->sourceBucket = $options["src-bucket"]; // If the source bucket name is provided, specify the sourceBucket parameter.
}
$request->sourceKey = $srcKey; // Specify the name of the source object.
// Perform the object copy operation.
$result = $client->copyObject($request);
// Display the object copy result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
);
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe the purpose of the script: copy an object in a bucket.
parser = argparse.ArgumentParser(description="copy object sample")
# Define command-line arguments, including the required region, destination bucket name, source bucket name, destination object name, source object name, source object version ID, and optional endpoint.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the destination object.', required=True)
parser.add_argument('--source_key', help='The name of the source object.', required=True)
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
parser.add_argument('--source_version_id', help='The version ID of the source object.',required=True)
def main():
# Parse command-line arguments to obtain the values entered by the user.
args = parser.parse_args()
# Load access credential information from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default SDK configurations to create a configuration object and set the authentication provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region property of the configuration object based on the command-line arguments.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint property in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configurations to initialize the OSS client and prepare for interaction with OSS.
client = oss.Client(cfg)
# Send a request to copy the specified object.
result = client.copy_object(oss.CopyObjectRequest(
bucket=args.bucket, # Destination bucket name.
key=args.key, # Destination object name.
source_key=args.source_key, # Source object name.
source_bucket=args.source_bucket, # Source bucket name.
source_version_id=args.source_version_id, # Version ID of the source object.
))
# Print the information about the operation result to confirm the request status.
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},'
)
# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
main() # The entry point of the script. The program flow starts here.
Usar ossutil
Para restaurar uma versão anterior usando o ossutil, consulte revert (restaurar versões).
Usar APIs RESTful
Também é possível chamar a API REST diretamente. CopyObject.