Exclua um único objeto, vários objetos por nome, objetos que correspondam a um prefixo ou um diretório inteiro.
Não é possível recuperar objetos excluídos. Prossiga com cautela.
Observações
Este tópico usa 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 do OSS, use um endpoint interno. Para mais informações sobre as regiões e os endpoints do OSS, consulte Regions and endpoints.
Este tópico demonstra como criar uma instância do 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 Create an OssClient instance.
Para excluir um objeto, é necessária a permissão
oss:DeleteObject. Para mais detalhes, consulte Grant a custom policy.
Excluir um único arquivo
O código a seguir exclui um objeto chamado exampleobject.txt de um bucket chamado examplebucket:
#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. For example, exampleobject.txt. The full path cannot contain the bucket name. */
/* To delete a folder, set ObjectName to the folder name. If the folder is not empty, you must delete all objects in the folder before you can delete the folder. */
std::string ObjectName = "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);
/* Delete the file. */
auto outcome = client.DeleteObject(request);
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 vários arquivos em lote
É possível excluir até 1.000 objetos por vez por nome, prefixo ou diretório.
Ao excluir vários arquivos, o sistema retorna os resultados em um dos dois modos a seguir. O modo padrão é o Verbose.
Modo Verbose: retorna uma lista de todos os arquivos excluídos.
Modo Basic: retorna apenas uma lista dos arquivos não excluídos.
Você também pode configurar regras de ciclo de vida para excluir objetos automaticamente. Para saber mais, consulte Lifecycle rules based on last modification time.
Excluir vários objetos com nomes especificados
O código a seguir exclui vários objetos por nome:
#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);
DeleteObjectsRequest request(BucketName);
/* Add the full paths of the objects to delete. */
request.addKey("yourObjectName1");
request.addKey("yourObjectName2");
/* Delete the files. */
auto outcome = client.DeleteObjects(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "DeleteObjects 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 objetos com o prefixo de nome de objeto especificado ou no diretório especificado
O código a seguir exclui objetos por prefixo ou um diretório inteiro:
Se o valor do parâmetro keyPrefix no código de exemplo a seguir for uma string vazia ou nula, o sistema excluirá todos os arquivos do bucket. Use esse recurso com cautela.
#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";
/* If you want to delete all files that have the prefix src, set the prefix to src. After you set the prefix to src, all non-folder files that have the prefix src, the src folder, and all files in the src folder are deleted. */
std::string keyPrefix = "src";
/* If you want to delete only the src folder and all files in it, set the prefix to src/. */
/* std::string keyPrefix = "src/"; */
/* 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);
std::string nextMarker = "";
bool isTruncated = false;
do {
/* List the files. */
ListObjectsRequest request(BucketName);
request.setPrefix(keyPrefix);
request.setMarker(nextMarker);
auto outcome = client.ListObjects(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "ListObjects fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
break;
}
for (const auto& object : outcome.result().ObjectSummarys()) {
DeleteObjectRequest request(BucketName, object.Key());
/* Delete the file. */
auto delResult = client.DeleteObject(request);
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
/* Release network resources. */
ShutdownSdk();
return 0;
}
Referências
Para acessar o código de exemplo completo para excluir um ou mais arquivos, consulte Exemplo no GitHub.
Operação da API para excluir um único arquivo: DeleteObject.
Operação da API para excluir vários arquivos: DeleteMultipleObjects.