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, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Criar uma instância OssClient.
Para excluir um objeto, é necessário ter a permissão
oss:DeleteObject. Para obter mais informações, consulte Conceder uma política personalizada.
Comportamento de exclusão em buckets com versionamento
Ao excluir um objeto de um bucket com versionamento, você precisa decidir se especificará um ID de versão.
-
Excluir um objeto sem especificar um ID de versão (exclusão temporária)
Caso você não especifique um ID de versão, 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 o
x-oss-delete-markeré verdadeiro, ox-oss-version-idretorna o ID de versão do marcador de exclusão. -
Excluir um objeto ao especificar um ID de versão (exclusão permanente)
Ao especificar um ID de versão, o OSS exclui permanentemente essa versão por meio do parâmetro
versionIdemparams. Para excluir a versão com ID nulo, definaparams['versionId'] = "null"emparams. O OSS interpreta a string "null" como o ID da versão de destino.
Excluir um único arquivo por nome
Excluir permanentemente um arquivo
O código a seguir demonstra 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 código a seguir demonstra como excluir temporariamente um objeto sem especificar um versionId. Uma versão de objeto excluída temporariamente pode ser recuperada.
#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
O código a seguir demonstra como excluir permanentemente várias versões de objetos ao especificar seus versionIds, ou como excluir marcadores de exclusão ao especificar seus versionIds. 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";
/* 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
O código a seguir demonstra como excluir temporariamente vários objetos sem especificar seus versionIds. Versões de objetos excluídas temporariamente 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";
/* 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
O código a seguir demonstra como excluir arquivos com um prefixo especificado.
#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 obter mais informações sobre a operação de API para excluir um único arquivo, consulte DeleteObject.
Para obter mais informações sobre a operação de API para excluir vários arquivos, consulte DeleteMultipleObjects.