You can use multiple methods to delete Object Storage Service (OSS) or Hadoop Distributed File System (HDFS) objects that you no longer need from a bucket. Deleted objects cannot be recovered. Exercise caution when you delete objects.
Deleted objects cannot be restored. Exercise caution when you delete objects.
To maintain OSS-HDFS stability and prevent data loss, do not delete objects from the
.dlsdata/
directory.
Delete a single object
OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
Delete OSS or HDFS objects.
Delete OSS objects
On the OSS Object tab, select an object and click Permanently Delete.
In the message that appears, click OK.
Delete HDFS objects
On the HDFS tab, find the object that you want to delete and click Permanently Delete.
NoteYou cannot delete multiple objects on the HDFS tab at a time. You can manually delete all objects on the HDFS tab one by one.
In the message that appears, click OK.
Command line interface
Before you use ossutil, you must install ossutil.
The following code provides an example of how to delete exampleobject in examplebucket
.
ossutil api delete-object --bucket examplebucket --key exampleobject
For more information, see delete-object.
ossbrowser
You can use ossbrowser to perform the same object-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, see ossbrowser 2.0 common operations.
OSS SDK
The following sample code provides examples on how to delete a single object by using OSS SDKs for common programming languages. For information about how to delete a single object by using OSS SDKs for other programming languages, see Overview.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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";
// 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 configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path of the object.
String objectName = "exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Delete the object or the directory. Before you delete a directory, make sure that the directory does not contain 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();
}
}
}
}
Node.js
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// 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 configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'examplebucket',
});
async function deleteObject() {
try {
// Specify the full path of the object. Do not include the bucket name in the full path.
const result = await client.delete('exampleobject.txt');
console.log(result);
} catch (error) {
console.log(error);
}
}
deleteObject();
Browser.js
OSS SDK for Browser.js is usually used in browsers. To prevent your AccessKey pair from being exposed, we recommend that you use temporary access credentials obtained from Security Token Service (STS) to access OSS. Temporary access credentials contain a security token and a temporary AccessKey pair. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For how to obtain temporary access credentials, see Authorize access.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="delete">Delete</button>
<!-- Import the SDK file -->
<script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
<script type="text/javascript">
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Specify the security token that you 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 that you want to delete. Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
let result = await client.delete('exampledir/exampleobject.txt');
console.log(result);
});
</script>
</body>
</html>
C#
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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";
// 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 configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Delete the object.
client.DeleteObject(bucketName, objectName);
Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete object failed. {0}", ex.Message);
}
Android-Java
// Create a delete request.
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object.
DeleteObjectRequest delete = new DeleteObjectRequest("examplebucket", "exampledir/exampleobject.txt");
// Asynchronously delete the object.
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 request exceptions.
if (clientExcepion != null) {
// Handle client-side exceptions, such as network exceptions.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Handle server-side exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
Object C
OSSDeleteObjectRequest * delete = [OSSDeleteObjectRequest new];
// Specify the name of the bucket. Example: examplebucket.
delete.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
delete.objectKey = @"exampleobject.txt";
OSSTask * deleteTask = [client deleteObject:delete];
[deleteTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
// ...
}
return nil;
}];
// Implement synchronous blocking to wait for the task to complete.
// [deleteTask waitUntilFinished];
C++
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access 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. */
std::string Endpoint = "yourEndpoint";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path. */
/* If you want to delete a directory, set ObjectName to the directory name. If the directory contains objects, delete all objects from the directory before you delete the directory. */
std::string ObjectName = "exampleobject.txt";
/* Initialize resources such as 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 configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
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;
return -1;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
C
#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";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object that you want to delete. Do not include the bucket name in the full path. */
const char *object_name = "exampleobject.jpg";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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 configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify 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 network resources and memory resources. */
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 value of the second parameter is 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;
}
Ruby
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',
# 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 configured.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket.
bucket = client.get_bucket('examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
bucket.delete_object('exampledir/exampleobject.txt')
Go
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
objectName string // Name of the object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the name of the object is specified.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to delete an object.
request := &oss.DeleteObjectRequest{
Bucket: oss.Ptr(bucketName), // Name of the bucket.
Key: oss.Ptr(objectName), // Name of the object.
}
// Execute the request and process the result.
result, err := client.DeleteObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to delete object %v", err)
}
// Display the result.
log.Printf("delete object result:%#v\n", result)
}
Python
import argparse
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser
parser = argparse.ArgumentParser(description="delete object sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
args = parser.parse_args() # Parse the command line parameters.
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If an endpoint is provided, specify the endpoint in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance.
client = oss.Client(cfg)
# Execute the request to delete the object, and specify the bucket name and object name.
result = client.delete_object(oss.DeleteObjectRequest(
bucket=args.bucket,
key=args.key,
))
# Display the HTTP status code in the response, the request ID, and the version ID and the delete marker of the object to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' version id: {result.version_id},'
f' delete marker: {result.delete_marker},'
)
if __name__ == "__main__":
main() # When the file is directly executed, the main function is called.
PHP
<?php
// Introduce autoload files to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define and describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];
// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command-line arguments.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain help information for the parameters.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // Exit the program if a required parameter is missing.
}
}
// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a DeleteObjectRequest object to delete the specified object.
$request = new Oss\Models\DeleteObjectRequest(bucket: $bucket, key: $key);
// Delete the object.
$result = $client->deleteObject($request);
// Display the result of the object deletion operation.
// Display the HTTP status code and request ID to check whether the request succeeded.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 204 indicates that the deletion succeeded.
'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
);
API
If your business requires a high level of customization, you can directly call RESTful API operations. To directly call an API operation, 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.
Delete multiple objects
You can delete up to 1,000 objects by sending a single request and send multiple requests to delete more objects.
OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
Delete OSS or HDFS objects.
Delete OSS objects
On the OSS Object tab, select multiple objects and click Permanently Delete.
In the message that appears, click OK.
Delete HDFS objects
On the HDFS tab, find the object that you want to delete and click Permanently Delete.
NoteYou cannot delete multiple objects on the HDFS tab at a time. You can manually delete all objects on the HDFS tab one by one.
In the message that appears, click OK.
Command-line tool ossutil
Before you use ossutil, you must install ossutil.
The following code provides an example of how to delete multiple objects in examplebucket
.
ossutil api delete-multiple-objects --bucket examplebucket --delete "{\"Quiet\":\"false\",\"Object\":[{\"Key\":\"multipart.data\"},{\"Key\":\"test.jpg\"}]}"
For more information, see delete-multiple-objects.
ossbrowser
You can use ossbrowser to perform the same object-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, see ossbrowser 2.0 common operations.
OSS SDK
The following sample code provides examples on how to delete multiple objects at a time by using OSS SDKs for common programming languages. For information about how to delete multiple objects at a time by using OSS SDKs for other programming languages, see Overview.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import java.io.UnsupportedEncodingException;
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";
// 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 configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Delete the objects.
// Specify the full paths of the multiple objects that you want to delete. Do not include the bucket name in the full paths of the objects.
List<String> keys = new ArrayList<String>();
keys.add("exampleobjecta.txt");
keys.add("testfolder/sampleobject.txt");
keys.add("exampleobjectb.txt");
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url"));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
try {
for(String obj : deletedObjects) {
String deleteObj = URLDecoder.decode(obj, "UTF-8");
System.out.println(deleteObj);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} 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();
}
}
}
}
Node.js
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// 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 configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'examplebucket',
});
async function deleteMulti() {
try {
// Specify the full paths of the objects that you want to delete and set the result mode to verbose. Do not include the bucket name in the full paths.
// let result = await client.deleteMulti(['exampleobject-1', 'exampleobject-2', 'testfolder/sampleobject.txt']);
// console.log(result);
// Specify the full paths of the objects that you want to delete and set the result mode to quiet. Do not include the bucket name in the full paths.
const result = await client.deleteMulti(['exampleobject-1', 'exampleobject-2', 'testfolder/sampleobject.txt'], {quiet: true});
console.log(result);
} catch (error) {
console.log(error);
}
}
deleteMulti();
Browser.js
OSS SDK for Browser.js is usually used in browsers. To prevent your AccessKey pair from being exposed, we recommend that you use temporary access credentials obtained from Security Token Service (STS) to access OSS. Temporary access credentials contain a security token and a temporary AccessKey pair. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For how to obtain temporary access credentials, see Authorize access.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="deleteAll">Delete All</button>
<!-- Import the 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({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Specify the security token that you obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the name of the bucket. Example: examplebucket.
bucket: "examplebucket",
});
const deleteAll = document.getElementById("deleteAll");
// Delete multiple objects.
deleteAll.addEventListener("click", async () => {
// Specify the names of the objects that you want to delete. Specify the full path of the objects. Do not include the bucket name in the full path.
let result = await client.deleteMulti([
"example.txt",
"exampleobject.txt",
"newexampleobject.txt",
]);
console.log(result);
result = await client.deleteMulti(
["example.txt", "exampleobject.txt", "newexampleobject.txt"],
{
// Set the quiet parameter to specify whether to list all objects that are deleted. If you set quiet to true, OSS does not return the list of the objects that are deleted. If you set quiet to false, OSS returns the list of the objects that are deleted.
quiet: true,
}
);
});
</script>
</body>
</html>
C#
using OSS = AlibabaCloud.OSS.V2; // Create an alias for Alibaba Cloud OSS SDK to simplify subsequent usage
var region = "cn-hangzhou"; // Required. Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou
var endpoint = null as string; // Optional. Specify the endpoint for accessing OSS. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com
var bucket = "your bucket name"; // Required. The name of the bucket
var keys = new List<String> // Required. The objects to delete
{
"your object key1",
"your object key2",
"your object key3"
};
// Load the default configuration of the OSS SDK, which automatically reads credential information (such as AccessKey) from environment variables
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set to use environment variables for credentials for authentication (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the bucket region in the configuration
cfg.Region = region;
// If an endpoint is specified, override the default endpoint
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance using the configuration information
using var client = new OSS.Client(cfg);
// Create a collection of objects to delete
var objects = new List<OSS.Models.DeleteObject>();
// Iterate through the list of object keys to delete (skip if keys is null)
foreach (var item in keys ?? [])
{
objects.Add(new OSS.Models.DeleteObject()
{
Key = item,
});
}
// Call the DeleteMultipleObjectsAsync method to execute the batch delete request
var result = await client.DeleteMultipleObjectsAsync(new OSS.Models.DeleteMultipleObjectsRequest()
{
Bucket = bucket,
Objects = objects
});
// Print the result information
Console.WriteLine("DeleteMultipleObjects done"); // Indicate the operation is complete
Console.WriteLine($"StatusCode: {result.StatusCode}"); // HTTP status code
Console.WriteLine($"RequestId: {result.RequestId}"); // RequestId for Alibaba Cloud troubleshooting
Console.WriteLine("Response Headers:"); // Response header information
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Iterate and print all response headers
Console.WriteLine("Key to be deleted:");
keys?.ToList().ForEach(x => Console.WriteLine(x)); // Print the list of deleted objects
Android-Java
// Specify the full paths of the objects that you want to delete. Do not include the bucket name in the full paths.
List<String> objectKeys = new ArrayList<String>();
objectKeys.add("exampleobject.txt");
objectKeys.add("testfolder/sampleobject.txt");
// Set isQuiet to true to return only a list of objects that failed to be deleted.
DeleteMultipleObjectRequest request = new DeleteMultipleObjectRequest("examplebucket", objectKeys, true);
oss.asyncDeleteMultipleObject(request, new OSSCompletedCallback<DeleteMultipleObjectRequest, DeleteMultipleObjectResult>() {
@Override
public void onSuccess(DeleteMultipleObjectRequest request, DeleteMultipleObjectResult result) {
Log.i("DeleteMultipleObject", "success");
}
@Override
public void onFailure(DeleteMultipleObjectRequest request, ClientException clientException, ServiceException serviceException) {
// Handle request exceptions.
if (clientException != null) {
// Handle client-side exceptions, such as network exceptions.
clientException.printStackTrace();
}
if (serviceException != null) {
// Handle server-side exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
Object C
// Specify the full paths of the objects that you want to delete. Do not include the bucket name in the full paths.
List<String> objectKeys = new ArrayList<String>();
objectKeys.add("exampleobject.txt");
objectKeys.add("testfolder/sampleobject.txt");
// Set isQuiet to true to return only a list of objects that failed to be deleted.
DeleteMultipleObjectRequest request = new DeleteMultipleObjectRequest("examplebucket", objectKeys, true);
oss.asyncDeleteMultipleObject(request, new OSSCompletedCallback<DeleteMultipleObjectRequest, DeleteMultipleObjectResult>() {
@Override
public void onSuccess(DeleteMultipleObjectRequest request, DeleteMultipleObjectResult result) {
Log.i("DeleteMultipleObject", "success");
}
@Override
public void onFailure(DeleteMultipleObjectRequest request, ClientException clientException, ServiceException serviceException) {
// Handle request exceptions.
if (clientException != null) {
// Handle client-side exceptions, such as network exceptions.
clientException.printStackTrace();
}
if (serviceException != null) {
// Handle server-side exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
C++
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access 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. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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 configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
DeleteObjectsRequest request(BucketName);
/* Add the full paths of multiple objects that you want to delete. */
request.addKey("yourObjectName1");
request.addKey("yourObjectName2");
/* Delete the objects. */
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 resources such as network resources. */
ShutdownSdk();
return 0;
}
C
#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";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full paths of the objects that you want to delete. Do not include the bucket name in the full paths. */
const char *object_name1 = "exampleobject1.jpg";
const char *object_name2 = "testobject2.png";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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 configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify 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 network resources and memory resources. */
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 value of the second parameter is 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 object1;
aos_string_t object2;
int is_quiet = 1;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object1, object_name1);
aos_str_set(&object2, object_name2);
/* Create a list of objects that you want to delete. */
aos_list_t object_list;
aos_list_t deleted_object_list;
oss_object_key_t *content1;
oss_object_key_t *content2;
aos_list_init(&object_list);
aos_list_init(&deleted_object_list);
content1 = oss_create_oss_object_key(pool);
aos_str_set(&content1->key, object_name1);
aos_list_add_tail(&content1->node, &object_list);
content2 = oss_create_oss_object_key(pool);
aos_str_set(&content2->key, object_name2);
aos_list_add_tail(&content2->node, &object_list);
/* Delete the objects in the list. `is_quiet` specifies whether to return the deletion result. */
resp_status = oss_delete_objects(oss_client_options, &bucket, &object_list, is_quiet, &resp_headers, &deleted_object_list);
if (aos_status_is_ok(resp_status)) {
printf("delete objects succeeded\n");
} else {
printf("delete objects 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;
}
Ruby
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',
# 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 configured.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket.
bucket = client.get_bucket('examplebucket')
# Specify the full paths of the objects that you want to delete. Do not include the bucket name in the full paths.
objs = ['my-object-1', 'my-object-2']
result = bucket.batch_delete_objects(objs)
# By default, the information about deleted objects is returned.
puts result #['my-object-1', 'my-object-2']
objs = ['my-object-3', 'my-object-4']
result = bucket.batch_delete_objects(objs, :quiet => true)
# Specify that the information about deleted objects is not returned.
puts result #[]
Go
package main
import (
"context"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
objects string // List of object names (separated with commas).
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objects, "objects", "", "The name of the objects (comma-separated).")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the list of object names is provided.
if len(objects) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, objects name required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Convert the list of object names into a slice.
var DeleteObjects []oss.DeleteObject
objectSlice := strings.Split(objects, ",")
for _, name := range objectSlice {
DeleteObjects = append(DeleteObjects, oss.DeleteObject{Key: oss.Ptr(strings.TrimSpace(name))})
}
// Create a request to delete multiple objects.
request := &oss.DeleteMultipleObjectsRequest{
Bucket: oss.Ptr(bucketName), // Name of the bucket.
Objects: DeleteObjects, // List of objects to delete.
}
// Execute the request and process the results.
result, err := client.DeleteMultipleObjects(context.TODO(), request)
if err != nil {
log.Fatalf("failed to delete multiple objects %v", err)
}
// Display the results.
log.Printf("delete multiple objects result:%#v\n", result)
}
Python
import argparse
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser
parser = argparse.ArgumentParser(description="delete multiple objects sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Note: If you want to delete multiple objects, add the command line parameter --key2, which specifies the name of the object.
parser.add_argument('--key2', help='The name of the object.', required=True)
def main():
# Parse the command line parameters
args = parser.parse_args()
# Obtain access credentials from environment variables for authentication
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and specify the credential provider
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration
cfg.region = args.region
# If an endpoint is provided, specify the endpoint in the configuration
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance
client = oss.Client(cfg)
# Define the list of objects to delete
# Note: If you want to delete multiple objects, extend the objects list in the following format
objects = [oss.DeleteObject(key=args.key), oss.DeleteObject(key=args.key2)]
# Execute the request to delete multiple objects, specifying the bucket name, encoding type, and object list
result = client.delete_multiple_objects(oss.DeleteMultipleObjectsRequest(
bucket=args.bucket,
encoding_type='url',
objects=objects,
))
# Display the HTTP status code in the response, the request ID, and information about the deleted objects to check whether the request is successful
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' key: {result.deleted_objects[0].key},'
f' version id: {result.deleted_objects[0].version_id},'
f' delete marker: {result.deleted_objects[0].delete_marker},'
f' delete marker version id: {result.deleted_objects[0].delete_marker_version_id},'
f' encoding type: {result.encoding_type},'
)
if __name__ == "__main__":
main() # When the file is directly executed, the main function is called
API
If your business requires a high level of customization, you can directly call RESTful API operations. To directly call an API operation, you must include the signature calculation in your code. For more information about the API operation that you can call to delete multiple objects at a time, see DeleteMultipleObjects.
Automatically delete objects based on lifecycle rules
When a bucket contains millions of objects, manually deleting objects is time-consuming and error-prone. You can use lifecycle rules to automatically delete objects on a regular basis based on conditions such as time and object prefixes, which reduces operational costs.