This topic describes how to delete a single object, multiple objects, or objects whose names contain a specified prefix from a versioned bucket.

Delete operations in a versioned bucket

When you delete an object from a versioned bucket, you must determine whether to specify a version ID in the request.

  • Delete an object without specifying a version ID (temporary deletion)

    By default, if you do not specify the version ID of the object that you want to delete in the request, Object Storage Service (OSS) does not delete the current version of the object but adds a delete marker to the object as the new current version. If you perform the GetObject operation on the object, OSS identifies the current version of the object as a delete marker and returns 404 Not Found. Additionally, the x-oss-delete-marker header and the x-oss-version-id header that indicates the version ID of the created delete marker are included in the response to the DeleteObject request.

    The value of the x-oss-delete-marker header in the response is true, which indicates that the x-oss-version-id value is the version ID of a delete marker.

  • Delete an object by specifying a version ID (permanent deletion)

    If you specify the version ID of the object that you want to delete in the request, OSS permanently deletes the version specified by the versionId field in the params parameter. To delete a version whose ID is null, add params['versionId'] = "null" to params in the request. OSS identifies the string "null" as the ID of the version to delete and deletes the version whose ID is null.

Delete a single object

The following examples demonstrate how to permanently or temporarily delete a single object from a versioned bucket.

  • Permanently delete an object from a versioned bucket
    The following code provides an example on how to permanently delete an object from a versioned bucket by specifying the version ID of the object in the request:
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the bucket name. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path of the object cannot contain the bucket name. 
            String objectName = "exampledir/object";
            String versionId  = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Delete the object that has the specified version ID. 
                ossClient.deleteVersion(bucketName, objectName , versionId);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • Temporarily delete an object from a versioned bucket
    The following code provides an example on how to temporarily delete an object from a versioned bucket by sending a request in which no version ID is specified:
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the bucket name. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path of the object cannot contain the bucket name. 
            String objectName = "exampledir/object";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Temporarily delete the object. A delete marker is added to the object. 
                ossClient.deleteObject(bucketName, objectName);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

Delete multiple objects

The following examples demonstrate how to permanently or temporarily delete multiple objects from a versioned bucket.

  • Permanently delete multiple objects from a versioned bucket
    The following code provides an example on how to permanently delete multiple objects or delete markers from a versioned bucket by specifying the version IDs of the objects or delete markers in the request:
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.DeleteVersionsRequest;
    import com.aliyun.oss.model.DeleteVersionsResult;
    import java.net.URLDecoder;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the bucket name. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path of the object cannot contain the bucket name. 
            String objectName = "exampledir/object";
            String object2Name = "exampledir/object2";
            String yourObjectNameVersionId  = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
            String yourObject2DelMarkerNameVersionId  = "MGE3N2M1YgICAof2D0BYiID3N2M1YTITI1NDQzOGY5NTN2M1YTI1NDQz****";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Permanently delete the objects or delete markers that have specified version IDs. 
                List<DeleteVersionsRequest.KeyVersion> keyVersionsList = new ArrayList<DeleteVersionsRequest.KeyVersion>();
                keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(objectName,yourObjectNameVersionId));
                keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(object2Name,yourObject2DelMarkerNameVersionId));
                DeleteVersionsRequest delVersionsRequest = new DeleteVersionsRequest(bucketName);
                delVersionsRequest.setKeys(keyVersionsList);
                // Initiate a deleteVersions request. 
                DeleteVersionsResult delVersionsResult = ossClient.deleteVersions(delVersionsRequest);
    
                // Display the deletion result. 
                for (DeleteVersionsResult.DeletedVersion delVer : delVersionsResult.getDeletedVersions()) {
                    String keyName = URLDecoder.decode(delVer.getKey(), "UTF-8");
                    String keyVersionId = delVer.getVersionId();
                    String keyDelMarkerId = delVer.getDeleteMarkerVersionId();
                    System.out.println("delete key: " + keyName);
                    System.out.println("delete key versionId: " + keyVersionId);
                    if(keyDelMarkerId != null && keyDelMarkerId.length() != 0){
                        System.out.println("delete key del_marker versionId: " + keyDelMarkerId);
                    }
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • Temporarily delete multiple objects from a versioned bucket
    The following code provides an example on how to delete multiple objects from a versioned bucket by sending a request in which no version IDs are specified:
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.DeleteObjectsRequest;
    import com.aliyun.oss.model.DeleteObjectsResult;
    import java.net.URLDecoder;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the bucket name. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path of the object cannot contain the bucket name. 
            String objectName = "exampledir/object";
            String object2Name = "exampledir/object2";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Delete multiple objects at a time. 
                List<String> KeysList = new ArrayList<String>();
                KeysList.add(objectName);
                KeysList.add(object2Name);
                DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName);
                request.setKeys(KeysList);
                // Initiate a deleteObjects request. 
                DeleteObjectsResult delObjResult = ossClient.deleteObjects(request);
    
                // Display the deletion result. 
                for (String o : delObjResult.getDeletedObjects()) {
                    String keyName = URLDecoder.decode(o, "UTF-8");
                    System.out.println("delete key name: " + keyName);
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

Delete objects whose names contain a specified prefix

The following code provides an example on how to delete objects whose names contain a specified prefix:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the bucket name. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the prefix that is contained in the names of the objects that you want to delete. 
        String prefix = "yourkeyPrefix";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // List the versions of all objects whose names contain the specified prefix and delete the versions. 
            String nextKeyMarker = null;
            String nextVersionMarker = null;
            VersionListing versionListing = null;
            do {
                ListVersionsRequest listVersionsRequest = new ListVersionsRequest()
                        .withBucketName(bucketName)
                        .withKeyMarker(nextKeyMarker)
                        .withVersionIdMarker(nextVersionMarker)
                        .withPrefix(prefix);

                versionListing = ossClient.listVersions(listVersionsRequest);
                if (versionListing.getVersionSummaries().size() > 0) {
                    List<DeleteVersionsRequest.KeyVersion> keyVersionsList = new ArrayList<DeleteVersionsRequest.KeyVersion>();
                    for (OSSVersionSummary ossVersion : versionListing.getVersionSummaries()) {
                        System.out.println("key name: " + ossVersion.getKey());
                        System.out.println("versionid: " + ossVersion.getVersionId());
                        System.out.println("Is delete marker: " + ossVersion.isDeleteMarker());
                        keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(ossVersion.getKey(), ossVersion.getVersionId()));
                    }
                    DeleteVersionsRequest delVersionsRequest = new DeleteVersionsRequest(bucketName).withKeys(keyVersionsList);
                    ossClient.deleteVersions(delVersionsRequest);
                }

                nextKeyMarker = versionListing.getNextKeyMarker();
                nextVersionMarker = versionListing.getNextVersionIdMarker();
            } while (versionListing.isTruncated());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

References

  • For more information about the API operation that you can call to delete a single object, see DeleteObject.
  • For more information about the API operation that you can call to delete multiple objects, see DeleteMultipleObjects.