Elimine un solo objeto, varios objetos por nombre, objetos que coincidan con un prefijo o un directorio completo.
Los objetos eliminados no se pueden recuperar. Proceda con precaución.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para otras configuraciones, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Create an OssClient instance.
Para eliminar un objeto, debe contar con el permiso
oss:DeleteObject. Para obtener más información, consulte Grant a custom policy.
Eliminar un solo archivo
El código a continuación elimina un objeto llamado exampleobject.txt de un bucket llamado 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;
}
Eliminar varios archivos en lote
Puede eliminar hasta 1,000 objetos a la vez por nombre, por prefijo o por directorio.
Al eliminar varios archivos, los resultados se devuelven en uno de los dos modos siguientes. El modo predeterminado es Verbose.
Modo Verbose: devuelve una lista de todos los archivos eliminados.
Modo Basic: devuelve únicamente una lista de los archivos cuya eliminación presentó errores.
También puede configurar reglas de ciclo de vida para eliminar objetos automáticamente. Para obtener más información, consulte Lifecycle rules based on last modification time.
Eliminar varios objetos con nombres específicos
El código a continuación elimina varios objetos por nombre:
#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;
}
Eliminar varios objetos con el prefijo de nombre de objeto especificado o en el directorio especificado
El código a continuación elimina objetos por prefijo o un directorio completo:
Si el valor del parámetro keyPrefix en el código de ejemplo a continuación es una cadena vacía o nulo, se eliminarán todos los archivos del bucket. Utilice esta función con precaución.
#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;
}
Referencias
Para consultar el código de ejemplo completo para eliminar uno o varios archivos, consulte el ejemplo en GitHub.
Operación de API para eliminar un solo archivo: DeleteObject.
Operación de API para eliminar varios archivos: DeleteMultipleObjects.