Todos los productos
Search
Centro de documentos

Object Storage Service:Eliminar archivos (SDK de C++)

Última actualización: Sep 24, 2026

En este tema se describe cómo eliminar un solo archivo (objeto), varios archivos y los archivos con un prefijo específico en un bucket que tiene habilitado el control de versiones.

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 ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • En este tema se muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, 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.

Comportamiento de eliminación en buckets con control de versiones

Cuando elimina un objeto de un bucket con control de versiones, debe decidir si especifica un identificador de versión.

  • Eliminar un objeto sin especificar un identificador de versión (eliminación temporal)

    Si no especifica un identificador de versión, OSS no elimina la versión actual. En su lugar, agrega un marcador de eliminación como la versión más reciente. Las solicitudes GetObject posteriores devuelven 404 Not Found junto con header:x-oss-delete-marker = true y el valor x-oss-version-id del marcador de eliminación en la respuesta.

    Cuando x-oss-delete-marker es verdadero, x-oss-version-id devuelve el identificador de versión del marcador de eliminación.

  • Eliminar un objeto al especificar un identificador de versión (eliminación permanente)

    Si especifica un identificador de versión, OSS elimina permanentemente esa versión mediante el parámetro versionId dentro de params. Para eliminar la versión con un identificador nulo, establezca params['versionId'] = "null" en params. OSS interpreta la cadena "null" como el identificador de versión de destino.

Eliminar un solo archivo por nombre

Eliminar un archivo de forma permanente

A continuación se muestra cómo eliminar permanentemente una versión específica de un objeto al indicar su versionId. Las versiones eliminadas de forma permanente no se pueden recuperar.

#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;
}

Eliminar un archivo de forma temporal

A continuación se muestra cómo eliminar temporalmente un objeto sin especificar un versionId. Una versión eliminada de forma temporal se puede recuperar.

#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;
}

Eliminar varios archivos por nombre

Eliminar archivos de forma permanente

A continuación se muestra cómo eliminar permanentemente varias versiones de objetos al especificar sus versionIds, o bien cómo eliminar marcadores de eliminación al indicar sus versionIds. Las versiones eliminadas de forma permanente no se pueden recuperar.

#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;
}

Eliminar archivos de forma temporal

A continuación se muestra cómo eliminar temporalmente varios objetos sin especificar sus versionIds. Las versiones eliminadas de forma temporal se pueden recuperar.

#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;
}

Eliminar archivos con un prefijo específico

A continuación se muestra cómo eliminar archivos que comparten un prefijo determinado.

#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;
}

Referencias

  • Para obtener más información sobre la operación de API que permite eliminar un solo archivo, consulte DeleteObject.

  • Para obtener más información sobre la operación de API que permite eliminar varios archivos, consulte DeleteMultipleObjects.