You can use multiple methods to delete objects that you no longer need from your buckets in Object Storage Service (OSS).

Warning
  • Objects cannot be restored after they are deleted. Exercise caution when you perform this operation.
  • To ensure the availability of the OSS-HDFS service or prevent data loss, do not delete objects from the .dlsdata/ directory in which OSS-HDFS data is stored in a bucket for which the OSS-HDFS service is enabled.

Deletion rules

OSS allows you to manually or automatically delete a single object or multiple objects based on the following rules:

  • Manual deletion
    • Delete a single object

      You can delete a single object by using the OSS console, ossbrowser, OSS SDKs, or ossutil.

    • Delete multiple objects

      You can delete up to 100 objects at a time in the OSS console or up to 1,000 objects at a time by using OSS SDKs. If you use ossutil or ossbrowser to delete multiple objects, you can delete an unlimited number of objects at a time.

  • Automatic deletion

    Automatic deletion allows you to delete multiple objects that match specified conditions. For example, you can delete objects that are last modified before a specified date, objects whose names contain a specific prefix, or objects that are stored in a specific bucket. To automatically delete objects, we recommend that you configure a lifecycle rule. After you configure the lifecycle rule, OSS automatically deletes specified objects based on the rule. This simplifies the deletion procedure and improves efficiency. For more information, see Overview.

Use the OSS console

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
  3. In the left-side navigation pane, choose Files > Files.
  4. Select a single object or multiple objects, and choose Batch Operation > Permanently Delete.
  5. In the message that appears, click OK.

Use ossbrowser

You can use ossbrowser to perform the same bucket-level operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to delete objects. For more information about how to use ossbrowser, see Use ossbrowser.

Use OSS SDKs

The following code provides examples on how to delete a single object by using OSS SDKs for common programming languages. For more information about how to delete a single object or multiple objects by using OSS SDKs for other programming languages, see Overview.

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 Object Storage Service (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 = "exampleobject.txt";

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

        try {
            // Delete the object or the directory. Before you delete a directory, make sure that the directory contains no objects. 
            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();
            }
        }
    }
}            
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (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. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket. 
$bucket = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
$object = "exampledir/exampleobject.txt";

try{
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

    $ossClient->deleteObject($bucket, $object);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . "OK" . "\n");          
const OSS = require('ali-oss')

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (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. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the bucket name. 
  bucket: 'examplebucket',
});

async function deleteFile () {
  try {
    // Specify the full path of the object. The full path of the object cannot contain the bucket name. 
    let result = await client.delete('exampleobject.txt');
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

deleteFile();            
# -*- coding: utf-8 -*-
import oss2

# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (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. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify the bucket name. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Delete the object. 
# Set yourObjectName to the full path of the object that you want to delete. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
# To delete a directory, set yourObjectName to the directory name. If the directory contains objects, you must delete all objects from the directory before you can delete the directory. 
bucket.delete_object('exampledir/exampleobject.txt')            
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
</head>

<body>
  <button id="delete">Delete An Object</button> 
  <!-- import an SDK file -->
  <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js"></script>
  <script type="text/javascript"> 
    const client = new OSS({
      // Set yourRegion to the endpoint of the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou. 
      region: 'yourRegion',
      // Specify the temporary AccessKey pair obtained from STS. 
      accessKeyId: 'yourAccessKeyId',
      accessKeySecret: 'yourAccessKeySecret',
      // Specify the security token obtained from STS. 
      stsToken: 'yourSecurityToken',
      // Specify the name of the bucket. Example: examplebucket. 
      bucket: "examplebucket",
    });

    const deleteSingle = document.getElementById("delete");   

    // Delete a single object. 
    deleteSingle.addEventListener("click", async () => {
      // Specify the name of the object to delete. // Specify the full path of the object. The path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
      let result = await client.delete('exampledir/exampleobject.txt');
      console.log(result);
    });

  </script>
</body>

</html>
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (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. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
var bucketName = "examplebucket";
var objectName = "exampleobject.txt";
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Delete the object. 
    client.DeleteObject(bucketName, objectName);
    Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Delete object failed. {0}", ex.Message);
}
// Create the delete request. 
// Specify the bucket name and the full path of the object that you want to delete. The full path of the object cannot contain bucket names.DeleteObjectRequest delete = new DeleteObjectRequest("examplebucket", "exampleobject.txt");// Delete the object asynchronously.OSSAsyncTask deleteTask = oss.asyncDeleteObject(delete, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
    @Override
    public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
        Log.d("asyncDeleteObject", "success!"); 
    }

    @Override
    public void onFailure(DeleteObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle exceptions.
        if (clientExcepion != null) {
            // Handle client exceptions, such as network exceptions.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle server exceptions.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
}); 
DeleteObjectRequest delete = new DeleteObjectRequest("examplebucket", "exampleobject.txt");
// Delete the object asynchronously. 
OSSAsyncTask deleteTask = oss.asyncDeleteObject(delete, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
    @Override
    public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
        Log.d("asyncDeleteObject", "success!");
    }

    @Override
    public void onFailure(DeleteObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle exceptions. 
        if (clientExcepion != null) {
            // Handle client exceptions, such as network exceptions.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle server exceptions.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (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. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the bucket name. Example: examplebucket. 
    bucketName := "examplebucket"
    // Set objectName to the full path of the object that you want to delete. The full path must contain the extension of the object name and cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
    // To delete a directory, set objectName to the directory name. If the directory contains objects, you must delete all objects from the directory before you can delete the directory. 
    objectName := "exampledir/exampleobject.txt"

    bucket, err := client.Bucket(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Delete a single object. 
    err = bucket.DeleteObject(objectName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}
OSSDeleteObjectRequest * delete = [OSSDeleteObjectRequest new];
// Specify the bucket name. 
delete.bucketName = @"examplebucket";
// Specify the full path of the object that you want to delete. The full path of the object cannot contain bucket names. 
delete.objectKey = @"exampleobject.txt";

OSSTask * deleteTask = [client deleteObject:delete];

[deleteTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        // ...
    }
    return nil;
}];

// [deleteTask waitUntilFinished];
        
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access Object Storage Service (OSS). */
    /* 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. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Example: exampleobject.txt. The full path of the object cannot contain the bucket name. */
    /* If you want to delete a directory, set ObjectName to the directory name. If the directory contains objects, you must delete all objects from the directory before you can delete the directory. */
    std::string ObjectName = "exampleobject.txt";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
   
    DeleteObjectRequest request(BucketName, ObjectName);

    /* Delete the object. */
    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;
        ShutdownSdk();
        return -1;
    }

    /* Release resources such as networks. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *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 Object Storage Service (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. */
const char *access_key_id = "yourAccessKeyId";
const char *access_key_secret = "yourAccessKeySecret";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object that you want to delete. The full path of the object cannot contain the bucket name. */
const char *object_name = "exampleobject.jpg";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize the aos_string_t data type. */
    aos_str_set(&options->config->endpoint, endpoint);
    aos_str_set(&options->config->access_key_id, access_key_id);
    aos_str_set(&options->config->access_key_secret, access_key_secret);
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Configure network parameters such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources such as networks and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is set to NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    /* Assign char* data to a bucket of the aos_string_t type. */
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    /* Delete the object. */
    resp_status = oss_delete_object(oss_client_options, &bucket, &object, &resp_headers);
    /* Determine whether the object is deleted. */
    if (aos_status_is_ok(resp_status)) {
        printf("delete object succeed\n");
    } else {
        printf("delete object failed\n");
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
  # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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. 
  access_key_id: 'AccessKeyId', access_key_secret: 'AccessKeySecret')

# Specify the bucket name. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# Specify the name of the object that you want to delete. 
bucket.delete_object('my-object')            

Use ossutil

For more information about how to delete objects by using ossutil, see Delete objects.

Use the RESTful API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code.

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.