Este tópico descreve como excluir um único arquivo (objeto), vários arquivos e arquivos com um prefixo especificado em um bucket com versionamento ativado.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Os exemplos aqui demonstram a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Criar uma instância OssClient.
A exclusão de um objeto requer a permissão
oss:DeleteObject. Para mais detalhes, visualize Conceder uma política personalizada.
Comportamento de exclusão em buckets com versionamento
Ao excluir um objeto de um bucket com versionamento, é necessário decidir se um ID de versão será especificado.
-
Excluir um objeto sem especificar um ID de versão (exclusão temporária)
Se nenhum ID de versão for especificado, o OSS não exclui a versão atual. Em vez disso, adiciona um marcador de exclusão como a versão mais recente. Solicitações GetObject subsequentes retornam
404 Not Foundcomheader:x-oss-delete-marker = truee ox-oss-version-iddo marcador de exclusão na resposta.Quando
x-oss-delete-markeré verdadeiro,x-oss-version-idretorna o ID de versão do marcador de exclusão. -
Excluir um objeto especificando um ID de versão (exclusão permanente)
Caso você especifique um ID de versão, o OSS exclui permanentemente essa versão usando o parâmetro
versionIdemparams. Para excluir a versão com ID nulo, definaparams['versionId'] = "null"emparams. O OSS trata a string "null" como o ID de versão alvo.
Excluir um único arquivo por nome
Excluir permanentemente um arquivo
O código a seguir mostra como excluir permanentemente uma versão específica de um objeto ao especificar seu versionId. Versões de objetos excluídas permanentemente não podem ser recuperadas.
#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;
}
Excluir temporariamente um arquivo
O exemplo abaixo ilustra como excluir temporariamente um objeto sem especificar um versionId. É possível recuperar uma versão de objeto excluída temporariamente.
#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);
DeleteObjectRequest request(BucketName, ObjectName);
/* Temporarily delete the object without specifying a versionId. This operation adds a delete marker to the object. */
auto outcome = client.DeleteObject(request);
/* View the versionId of the returned delete marker. */
if (outcome.isSuccess()) {
std::cout << "versionid:" << outcome.result().VersionId() << ",DeleteMarker:" << outcome.result().DeleteMarker() << std::endl;
}
else {
/* 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;
}
Excluir vários arquivos por nome
Excluir permanentemente arquivos
Este trecho de código demonstra a exclusão permanente de múltiplas versões de objetos mediante a especificação de seus versionIds, ou a remoção de marcadores de exclusão informando seus respectivos versionIds. Não é possível recuperar versões de objetos excluídas permanentemente.
#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";
/* 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);
DeleteObjectVersionsRequest request(BucketName);
/* Add the versionIds of the objects or delete markers to delete. */
ObjectIdentifier obj1("yourObject1Name");
obj1.setVersionId("yourVersionId");
ObjectIdentifier obj2("yourObject2Name");
obj2.setVersionId("obj2_del_marker_versionid");
request.addObject(obj1);
request.addObject(obj2);
/* Batch delete the objects with the specified versionIds or the objects associated with the specified delete marker versionIds. */
auto outcome = client.DeleteObjectVersions(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "DeleteObjectVersions fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Excluir temporariamente arquivos
A amostra de código a seguir ensina como excluir temporariamente vários objetos sem informar seus versionIds. Versões de objetos excluídas temporariamente são recuperáveis.
#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";
/* 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);
DeleteObjectVersionsRequest request(BucketName);
/* Specify the names of the objects to delete. */
ObjectIdentifier obj1("ObjectName1");
ObjectIdentifier obj2("ObjectName2");
ObjectIdentifier obj3("ObjectName3");
request.addObject(obj1);
request.addObject(obj2);
request.addObject(obj3);
/* Delete the objects. */
auto outcome = client.DeleteObjectVersions(request);
if (outcome.isSuccess()) {
for (auto const &obj : outcome.result().DeletedObjects()) {
std::cout << "versionid:" << obj.VersionId() << ",DeleteMarker:" << obj.DeleteMarker() << std::endl;
}
}
else {
/* Handle exceptions. */
std::cout << "DeleteObjectVersions fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Excluir arquivos com um prefixo especificado
Utilize o código abaixo para excluir arquivos que possuam um determinado prefixo.
#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";
/* 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);
ListObjectVersionsRequest request(BucketName);
bool IsTruncated = false;
do {
request.setPrefix("yourkeyPrefix");
auto outcome = client.ListObjectVersions(request);
if (outcome.isSuccess()) {
/* View the version information of the listed objects and delete markers. */
for (auto const &marker : outcome.result().DeleteMarkerSummarys()) {
client.DeleteObject(DeleteObjectRequest(BucketName, marker.Key(), marker.VersionId()));
}
/* List the version information of all objects with the specified prefix and delete these files. */
for (auto const &obj : outcome.result().ObjectVersionSummarys()) {
client.DeleteObject(DeleteObjectRequest(BucketName, obj.Key(), obj.VersionId()));
}
}
else {
std::cout << "ListObjectVersions fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
break;
}
request.setKeyMarker(outcome.result().NextKeyMarker());
request.setVersionIdMarker(outcome.result().NextVersionIdMarker());
IsTruncated = outcome.result().IsTruncated();
} while (IsTruncated);
/* Release network resources. */
ShutdownSdk();
return 0;
}
Referências
Para detalhes sobre a operação de API destinada a excluir um único arquivo, consulte DeleteObject.
Saiba mais sobre a operação de API para excluir múltiplos arquivos em DeleteMultipleObjects.