複数の方法を使用して、必要のないObject Storage Service (OSS) またはHDFSオブジェクトをバケットから削除できます。
削除したオブジェクトを元に戻すことはできません。 作業は慎重に行ってください。
OSS-HDFSの安定性を維持し、データの損失を防ぐために、
. dlsdata /
ディレクトリに移動します。
削除ルール
OSSでは、次のルールに基づいて1つ以上のオブジェクトを手動または自動で削除できます。
手動削除
OSSコンソール、OSS API、OSS SDK、ossbrowser、またはossutilを使用して、単一のオブジェクトまたは複数のオブジェクトを削除できます。 1つのリクエストを送信し、複数のリクエストを送信することで最大1,000個のオブジェクトを削除して、さらに多くのオブジェクトまたはディレクトリを削除できます。
自動削除
特定の日付より前に最後に変更されたオブジェクト、名前に特定のプレフィックスが含まれているオブジェクト、または特定のバケットに格納されているオブジェクトを削除する必要がある場合は、自動削除のライフサイクルルールを設定することを推奨します。 設定が完了すると、ルールに基づいて指定されたオブジェクトが自動的に削除されます。 これは、削除手順を単純化し、効率を改善する。 詳細については、「ライフサイクル」をご参照ください。
手順
OSSコンソールの使用
OSSコンソールにログインします。
左側のナビゲーションウィンドウで、バケットリスト をクリックします。 [バケット] ページで、目的のバケットを見つけてクリックします。
左側のナビゲーションツリーで、ファイル>オブジェクトを選択します。
OSSまたはHDFSオブジェクトを削除します。
OSSオブジェクトの削除
OSS オブジェクトタブで、1つ以上のオブジェクトを選択し、完全に削除オブジェクトリストの下にある完全に削除をクリックします。
表示されるメッセージで、OK をクリックします。
HDFSオブジェクトの削除
[HDFS] タブで、削除するオブジェクトを見つけて、[操作] 列の 完全に削除 をクリックします。
説明HDFSタブで複数のオブジェクトを一度に削除することはできません。 HDFSタブのすべてのオブジェクトを1つずつ手動で削除できます。
表示されるメッセージで、OK をクリックします。
ossbrowserの使用
ossbrowserを使用して、OSSコンソールで実行できるのと同じオブジェクトレベルの操作を実行できます。 ossbrowserの画面上の指示に従って、オブジェクトを削除できます。 詳細については、「ossbrowserの使用」をご参照ください。
OSS SDKの使用
次のサンプルコードは、一般的なプログラミング言語のOSS SDKを使用して単一のオブジェクトを削除する方法の例を示しています。 他のプログラミング言語のOSS SDKを使用して1つ以上のオブジェクトを削除する方法については、「概要」をご参照ください。
Java
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
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";
// 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.
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();
}
}
}
}
PHP
<?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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// 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 name of the bucket. Example: examplebucket.
$bucket = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
$object = "exampledir/exampleobject.txt";
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->deleteObject($bucket, $object);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");
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();
Python
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# 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"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Delete the object.
# Specify the full path of the object that you want to delete. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
# To delete a directory, specify 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')
HMTL
ほとんどの場合、ブラウザではOSS SDK for Browser.jsが使用されます。 AccessKeyペアが公開されないようにするには、Security Token Service (STS) から取得した一時的なアクセス資格情報を使用してOSSにアクセスすることを推奨します。 一時的なアクセス資格情報は、AccessKeyペアとセキュリティトークンで構成されます。 AccessKey ペアは、AccessKey ID と AccessKey Secret で構成されます。 一時的なアクセス資格情報を取得する方法の詳細については、「一時的なアクセス権限付与にSTSを使用する」をご参照ください。
<!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;
// 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);
c.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());
}
}
});
Go
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// 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.
// 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. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket. 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 but cannot contain the bucket name. Example: exampledir/exampleobject.txt.
// 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.
objectName := "exampledir/exampleobject.txt"
// Create a bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Delete the object.
err = bucket.DeleteObject(objectName)
if err != nil {
log.Fatalf("Failed to delete object '%s': %v", objectName, err)
}
log.Printf("Successfully deleted object: %s\n", objectName)
}
オブジェクト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;
}
ルビー
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')
ossutilの使用
ossutilを使用してオブジェクトを削除する方法については、「rm」をご参照ください。
OSS APIの使用
ビジネスで高度なカスタマイズが必要な場合は、RESTful APIを直接呼び出すことができます。 APIを直接呼び出すには、コードに署名計算を含める必要があります。
単一のオブジェクトを削除するために呼び出すことができるAPI操作の詳細については、「DeleteObject」をご参照ください。
複数のオブジェクトを削除するために呼び出すことができるAPI操作の詳細については、「DeleteMultipleObjects」をご参照ください。