Você pode usar vários métodos para excluir objetos desnecessários do Object Storage Service (OSS) ou HDFS de um bucket.
Objetos excluídos não podem ser recuperados. Proceda com cautela.
Regras de exclusão
O OSS permite excluir um ou mais objetos manual ou automaticamente conforme as regras a seguir:
-
Exclusão manual
É possível excluir um único objeto ou vários objetos usando o console do OSS, a API do OSS, os SDKs do OSS, o ossbrowser ou o ossutil. Uma única solicitação permite excluir até 1.000 objetos. Envie múltiplas solicitações para excluir mais objetos ou diretórios.
-
Exclusão automática
Se você precisar excluir objetos modificados pela última vez antes de uma data específica, objetos cujos nomes contenham um prefixo específico ou objetos armazenados em um bucket específico, configure uma regra de ciclo de vida para exclusão automática. Após a configuração, o OSS exclui automaticamente os objetos especificados com base na regra. Isso simplifica o procedimento de exclusão e aumenta a eficiência. Para obter mais informações, consulte Regras de ciclo de vida.
Métodos
Usar o console do OSS
Faça login no console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página exibida, clique em nome do bucket desejado.
No painel de navegação à esquerda, escolha Object Management > Objects.
-
Exclua objetos do OSS ou HDFS.
Excluir objetos do OSS
Na aba OSS Object, selecione um ou mais objetos e clique em Permanently Delete abaixo da lista de objetos.
Na mensagem exibida, clique em OK.
Excluir objetos do HDFS
-
Na aba HDFS, localize o objeto que deseja excluir e clique em Permanently Delete na coluna Actions.
NotaNão é possível excluir vários objetos simultaneamente na aba HDFS. Exclua manualmente todos os objetos na aba HDFS um por um.
Na mensagem exibida, clique em OK.
Usar a ferramenta de gerenciamento gráfico ossbrowser
O ossbrowser oferece suporte a operações no nível de objeto semelhantes às suportadas pelo console. Siga as instruções na interface do ossbrowser para concluir a exclusão de arquivos. Para saber como usar o ossbrowser, consulte Operações comuns do ossbrowser 2.0.
Usar o ossbrowser
O ossbrowser permite realizar as mesmas operações no nível de objeto disponíveis no console do OSS. Siga as instruções na tela do ossbrowser para excluir objetos. Para obter mais informações, consulte Operações comuns.
Usar os SDKs do OSS
Os exemplos de código a seguir mostram como excluir um único objeto usando os SDKs do OSS para linguagens de programação comuns. Para obter informações sobre como excluir um ou mais objetos usando os SDKs do OSS para outras linguagens de programação, consulte Introdução.
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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket',
});
async function deleteObject() {
try {
// Specify the full path of the object. The full path cannot contain the bucket name.
const result = await client.delete('exampleobject.txt');
console.log(result);
} catch (error) {
console.log(error);
}
}
deleteObject();
Browser.js
Geralmente, o SDK do OSS para Browser.js é usado em navegadores. Para evitar que seu par de AccessKeys seja exposto, recomendamos o uso de credenciais de acesso temporárias obtidas pelo Security Token Service (STS) para acessar o OSS. As credenciais de acesso temporárias consistem em um par de AccessKeys e um token de segurança. Um par de AccessKeys é composto por um AccessKey ID e um AccessKey secret. Para saber como obter credenciais de acesso temporárias, consulte Autorizar acesso (SDK Browser.js).
<!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({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from STS.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token (SecurityToken) obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
const deleteSingle = document.getElementById("delete");
// Delete a single file.
deleteSingle.addEventListener("click", async () => {
// Specify the name of the object to delete. The object name must be the full path of the object, not including the bucket name. For 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 bucket name (for example, examplebucket) and the full path of the object (for example, exampledir/exampleobject.txt). The full path of the object cannot contain the bucket name.
DeleteObjectRequest delete = new DeleteObjectRequest("examplebucket", "exampledir/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) {
// Request error.
if (clientExcepion != null) {
// A client exception occurred, such as a network exception.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// A server exception occurred.
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 the OSS account information. */
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. For example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. For example, exampleobject.txt. The full path cannot contain the bucket name. */
/* To delete a folder, set ObjectName to the folder name. If the folder is not empty, you must delete all objects in the folder before you can delete the folder. */
std::string ObjectName = "exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
DeleteObjectRequest request(BucketName, ObjectName);
/* Delete the file. */
auto outcome = client.DeleteObject(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "DeleteObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
C
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the file to delete. The full path cannot include the bucket name. */
const char *object_name = "exampleobject.jpg";
/* Set yourRegion to the Region ID of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize an aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
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"));
// Configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether a canonical name (CNAME) is used. A value of 0 indicates that no CNAME is used. */
options->config->is_cname = 0;
/* Set 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 at the program entry to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool (pool) for memory management is equivalent to apr_pool_t. Its implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a memory pool. The second parameter is NULL, which indicates that the new pool does not inherit from another memory pool. */
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 memory to options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t object;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
/* Assign the char* type data to the aos_string_t type bucket. */
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
/* Delete the file. */
resp_status = oss_delete_object(oss_client_options, &bucket, &object, &resp_headers);
/* Check whether the file 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 releases the memory allocated to resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
Ruby
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Set Endpoint to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Set the bucket name. For example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Set the full path of the object. For example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
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 // The bucket's region.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// The init function initializes command-line arguments.
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 arguments.
flag.Parse()
// Check if the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check if the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configuration and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to delete the object.
request := &oss.DeleteObjectRequest{
Bucket: oss.Ptr(bucketName), // The bucket name.
Key: oss.Ptr(objectName), // The object name.
}
// Delete the object and process the result.
result, err := client.DeleteObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to delete object %v", err)
}
// Print the result.
log.Printf("delete object result:%#v\n", result)
}
Python
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="delete object sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is not required.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
args = parser.parse_args() # Parse command-line arguments.
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If the endpoint parameter is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client using the configured information.
client = oss.Client(cfg)
# Execute a request to delete an object. Specify the bucket name and object name.
result = client.delete_object(oss.DeleteObjectRequest(
bucket=args.bucket,
key=args.key,
))
# Print the status code, request ID, version ID, and delete marker of the request 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() # The entry point of the script. The main function is called when the file is directly run.
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.
);
Usar o ossutil
Use o ossutil para excluir objetos. Para obter informações sobre a instalação do ossutil, consulte Instalar o ossutil.
-
O exemplo a seguir mostra como excluir exampleobject em
examplebucket.ossutil api delete-object --bucket examplebucket --key exampleobjectPara obter mais informações, consulte delete-object.
-
Este exemplo demonstra como excluir vários objetos em
examplebucket.ossutil api delete-multiple-objects --bucket examplebucket --delete "{\"Quiet\":\"false\",\"Object\":[{\"Key\":\"multipart.data\"},{\"Key\":\"test.jpg\"}]}"Para obter mais informações, consulte delete-multiple-objects.
Operações de API relacionadas
Os métodos descritos acima são implementados com base na API RESTful. Você pode chamá-la diretamente caso seu negócio exija um alto nível de personalização. Para chamar uma API diretamente, inclua o cálculo da assinatura no seu código.
Para obter mais informações sobre a operação de API usada para excluir um único objeto, consulte DeleteObject.
Para obter mais informações sobre a operação de API que exclui vários objetos simultaneamente, consulte DeleteMultipleObjects.