Ao ativar o versionamento de um bucket, os objetos existentes mantêm seu conteúdo e suas ACLs. O versionamento evita substituições e exclusões acidentais, além de permitir a consulta e a restauração de versões históricas dos objetos.
Notas de uso
Ao fazer upload, listar, baixar, excluir ou restaurar objetos em um bucket com versionamento ativado, uma regra de ciclo de vida que faz a transição de um objeto para uma classe de armazenamento diferente não cria uma nova versão. Para mais informações, consulte Versioning.
Fazer upload de objetos
Ao fazer upload de um objeto para um bucket com versionamento ativado, o OSS cria automaticamente uma nova versão. Se já existir um objeto com o mesmo nome, o objeto existente é mantido como uma versão histórica e o objeto recém-enviado se torna a versão atual.
Usar o console do OSS
Faça login no OSS console.
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.
Parâmetro
Descrição
Upload To
Especifique o caminho de armazenamento do objeto.
-
Current Directory: Faça o upload do objeto para o diretório atual.
-
Specified Directory: Faça o upload do objeto para um diretório específico. Você deve inserir um nome de diretório. Se o diretório não existir, o OSS o criará automaticamente e fará o upload do objeto para ele.
O nome do diretório deve atender aos seguintes requisitos:
-
O nome deve ter de 1 a 254 caracteres e ser codificado em UTF-8.
-
O nome não pode começar com uma barra (/) ou uma barra invertida (\).
-
O nome não pode conter barras consecutivas (/).
-
O nome não pode ser 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 do objeto tem permissões de leitura e gravação. Outros usuários, incluindo usuários anônimos, têm apenas permissão de leitura. Isso pode resultar em vazamento de dados e custos inesperadamente altos. Prossiga com cautela.
-
Public Read/Write: Todos os usuários, incluindo usuários 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 no seu objeto. Evite conceder permissões públicas de leitura e gravação, a menos que seja estritamente necessário.
Files to Upload
Selecione os arquivos ou pastas que deseja enviar.
Clique em Select Files ou Select Folders para selecionar arquivos ou pastas locais. Você também pode arrastar os arquivos ou pastas para a área Files to Upload.
Se uma pasta selecionada contiver arquivos que você não deseja enviar, localize-os na lista e clique em Remove na coluna Actions.
Importante-
Se você fizer o upload de um objeto para um bucket com o versionamento desativado e o objeto tiver o mesmo nome de um objeto existente, o objeto existente será substituído.
-
Se você fizer o upload de um objeto para um bucket com o versionamento ativado e o objeto tiver o mesmo nome de um objeto existente, o novo objeto se tornará a versão atual e o objeto existente se tornará 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.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: Fornece armazenamento de objetos confiável, altamente disponível e de alto desempenho para dados acessados com frequência. Esta classe de armazenamento é adequada para vários cenários, como aplicativos de imagens sociais e de compartilhamento, aplicativos de áudio e vídeo, grandes sites e análise de big data. A classe de armazenamento Standard oferece suporte a armazenamento redundante de zona (ZRS) e armazenamento localmente redundante (LRS).
-
IA: Fornece um service de armazenamento de objetos altamente durável a um custo de armazenamento menor. Esta classe de armazenamento tem um tamanho mínimo faturável de 64 KB e um período mínimo de armazenamento de 30 dias. Os dados podem ser acessados em tempo real, mas há taxas de recuperação de dados. Esta classe é adequada para cenários com baixa frequência de acesso, por exemplo, uma ou duas vezes por mês, em média. A classe de armazenamento IA oferece suporte a armazenamento redundante de zona e armazenamento localmente redundante.
-
Archive: Fornece um service de armazenamento de objetos altamente durável a um custo de armazenamento extremamente baixo. Esta classe tem um tamanho mínimo faturável de 64 KB e um período mínimo de armazenamento de 60 dias. Você pode acessar objetos Archive restaurando-os primeiro (o que leva cerca de um minuto) ou acessando-os diretamente. Há taxas tanto para restauração quanto para leituras diretas. Esta classe é adequada para cenários de arquivamento de dados de longo prazo, como dados de arquivo, imagens médicas, materiais científicos e filmagens. A classe de armazenamento Archive oferece suporte a armazenamento redundante de zona e armazenamento localmente redundante.
-
Cold Archive: Fornece um service de armazenamento de objetos altamente durável a um custo de armazenamento menor que o Archive. Esta classe tem um tamanho mínimo faturável de 64 KB e um período mínimo de armazenamento de 180 dias. Os objetos Cold Archive devem ser restaurados antes que você possa acessá-los. O tempo de restauração depende do tamanho do objeto e do modo de restauração. Taxas de recuperação de dados e taxas de solicitação são incorridas para a restauração. Esta classe é adequada para armazenar dados frios por um período prolongado, como dados que requerem retenção de longo prazo para fins de conformidade, dados brutos acumulados nas áreas de big data e IA, ativos de mídia de longo prazo nas indústrias de cinema e televisão, e vídeos arquivados no setor de educação online. A classe de armazenamento Cold Archive oferece suporte apenas a armazenamento localmente redundante.
-
Deep Cold Archive: Fornece um service de armazenamento de objetos altamente durável a um custo de armazenamento menor que o Cold Archive. Esta classe tem um tamanho mínimo faturável de 64 KB e um período mínimo de armazenamento de 180 dias. Os objetos Deep Cold Archive devem ser restaurados antes que você possa acessá-los. O tempo de restauração depende do tamanho do objeto e do modo de restauração. Taxas de recuperação de dados e taxas de solicitação são incorridas para a restauração. Esta classe é adequada para armazenar dados extremamente frios por um período prolongado, como dados brutos acumulados nas áreas de big data e IA, ativos de mídia de longo prazo, arquivos regulatórios e de conformidade, e substituição de fitas. A classe de armazenamento Deep Cold Archive oferece suporte apenas a armazenamento localmente redundante.
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 OSS. Para proteção adicional, essas chaves são criptografadas com uma chave mestra.
-
KMS: Use a chave mestra do cliente (CMK) padrão gerenciada pelo KMS ou uma CMK especificada para criptografia e descriptografia.
Para usar a criptografia KMS, ative o KMS primeiro. Purchase a Dedicated KMS instance.
A seguir, descrevemos o parâmetro CMK:
A chave de criptografia está no formato
<alias>(CMK ID), onde<alias>é o alias da CMK e CMK ID é o ID da CMK. Valores válidos:-
alias/acs/oss(CMK ID): A CMK padrão gerenciada pelo KMS é usada para gerar chaves diferentes para criptografar objetos diferentes. Os objetos são descriptografados automaticamente quando baixados.
-
alias/<cmkname>(CMK ID): Esta opção usa uma CMK especificada para gerar uma chave de criptografia exclusiva para cada objeto. Os metadados do objeto armazenam o ID da CMK. Quando um usuário com as permissões necessárias baixa o objeto, o OSS o descriptografa automaticamente.
<cmkname>é o alias opcional da CMK que você especificou ao criá-la.Antes de usar um ID de CMK especificado, crie uma chave regular ou uma chave externa na mesma região do bucket no console do KMS. Para mais informações, consulte Create a CMK.
-
-
Encryption Algorithm: Apenas o AES256 é suportado.
User-defined Metadata
Adicione informações descritivas ao objeto. Você pode adicionar várias entradas de metadados definidos pelo usuário. O tamanho total de todos os metadados definidos pelo usuário não pode exceder 8 KB. Cada chave de metadados definida pelo usuário deve ter o prefixo
x-oss-meta-e um valor atribuído. Exemplo: x-oss-meta-location:hangzhou. -
-
Clique em Upload Object.
Você pode acompanhar o progresso do upload de cada arquivo na aba Upload Tasks do painel Task List.
-
Usar os SDKs do Alibaba Cloud
O código a seguir faz o upload de um objeto para um bucket com versionamento ativado. Para outros SDKs, consulte SDK overview.
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 o ossutil
Para fazer upload de objetos para um bucket com versionamento ativado usando o ossutil, consulte cp (upload objects).
Usar uma API REST
Você também pode 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 de objetos, incluindo objetos marcados como excluídos.
A operação GetBucket (ListObject) retorna apenas as versões atuais dos objetos e exclui os objetos marcados como excluídos.
-
Uma única solicitação GetBucketVersions (ListObjectVersions) retorna até 1.000 versões de objetos. Para recuperar todas as versões, envie várias solicitações.
Por exemplo, se um bucket contiver duas chaves,
example.jpgephoto.jpg, ondeexample.jpgtem 900 versões ephoto.jpgtem 500 versões, uma única solicitação listará todas as 900 versões deexample.jpge as primeiras 100 versões dephoto.jpg. Os resultados são classificados por chave em ordem lexicográfica e, em seguida, por versão.
O GetBucketVersions (ListObjectVersions) retorna todas as versões de todos os objetos no bucket, incluindo objetos marcados como excluídos. O GetBucket (ListObject) retorna apenas as versões atuais dos objetos e exclui os objetos marcados como excluídos.
Console do OSS
Faça login no OSS console.
-
Clique em Buckets e, em seguida, clique no nome do bucket de destino.
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 SDK introduction.
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 (List resources at the account level).
API RESTful
Você também pode chamar a API REST diretamente. ListObjectVersions (GetBucketVersions).
Baixar objetos
Você pode baixar a versão atual ou uma versão específica de um objeto.
Uma solicitação GET sem um ID de versão retorna a versão atual.
Se a versão atual estiver marcada como excluída, a solicitação GET retornará 404 Not Found.
Uma solicitação GET com um ID de versão retorna a versão histórica especificada.
Usar o console do OSS
Faça login no OSS console.
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 SDK overview.
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 o ossutil
Para baixar objetos de um bucket com versionamento ativado usando o ossutil, consulte cp (download objects).
Usar uma API REST
Você também pode chamar a API REST diretamente. GetObject.
Excluir objetos
Em um bucket com versionamento ativado, você pode excluir permanentemente um objeto especificando seu ID de versão ou configurando uma regra de ciclo de vida. Se você excluir um objeto sem especificar um ID de versão, o objeto será marcado como excluído e suas versões históricas não serão afetadas.
Após ativar o versionamento, excluir um objeto sem especificar um ID de versão não exclui suas versões atuais ou não atuais por padrão.
-
Não ative o service OSS-HDFS e o versionamento no mesmo bucket. Isso pode levar à instabilidade do service. Para garantir uma operação estável, suspenda o versionamento o mais rápido possível e configure uma regra de ciclo de vida para limpar os marcadores de exclusão.
How do I handle a bucket for which both OSS-HDFS and versioning are enabled?.
Expiration: Aplica-se à versão atual de um objeto e retém a versão atual expirada como uma versão histórica.NoncurrentVersionExpiration: Aplica-se a versões não atuais de um objeto. Esta ação exclui permanentemente essas versões.
Para usar o versionamento com regras de ciclo de vida, consulte Lifecycle configuration elements.
Se você não especificar um ID de versão, o objeto será marcado como excluído. As versões históricas não são afetadas e podem ser restauradas posteriormente.
Se você especificar um ID de versão, o OSS excluirá permanentemente a versão do objeto especificada.
Console do OSS
Para minimizar os custos de armazenamento, recomendamos que você exclua as versões anteriores dos objetos que não são mais necessários o mais breve possível.
Versões não atuais de objetos não podem ser restauradas após serem excluídas permanentemente. Prossiga com cautela.
Faça login no OSS console.
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.
Você também pode selecionar várias versões não atuais e clicar em Permanently Delete na parte inferior da página.
-
Clique em OK.
Você também pode configurar uma regra de ciclo de vida para excluir periodicamente as versões não atuais. Overview of lifecycle rules.
SDK do OSS
O código a seguir exclui uma versão específica de um bucket com versionamento ativado. Para outros SDKs, consulte SDK overview.
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 (delete).
API REST
Você também pode chamar a API REST diretamente. DeleteObject.
Restaurar objetos
Quando o versionamento está ativado, o OSS retém todas as versões dos objetos. Você pode restaurar uma versão anterior para torná-la a versão atual.
Você pode restaurar uma versão anterior de duas maneiras:
-
Copiar a versão anterior do objeto
Copie a versão histórica especificada para o mesmo bucket. O objeto copiado se torna a versão atual e todas as versões históricas existentes são mantidas.
-
Excluir permanentemente a versão atual do objeto
Exclua permanentemente a versão atual especificando seu ID de versão. A próxima versão histórica se torna a versão atual.
Uma versão excluída permanentemente não pode ser recuperada. Recomendamos restaurar as versões anteriores copiando-as.
Usar o console do OSS
Faça login no OSS console.
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.
ImportanteVocê pode restaurar apenas uma versão de objeto por vez. Um marcador de exclusão não pode ser restaurado.
-
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 SDK overview.
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 o ossutil
Para restaurar uma versão anterior usando o ossutil, consulte revert (restore versions).
Usar APIs RESTful
Você também pode chamar a API REST diretamente. CopyObject.