tencent cloud

Cloud Object Storage

동향 및 공지
릴리스 노트
제품 공지
제품 소개
제품 개요
기능 개요
적용 시나리오
제품 장점
기본 개념
리전 및 액세스 도메인
규격 및 제한
제품 요금
과금 개요
과금 방식
과금 항목
프리 티어
과금 예시
청구서 보기 및 다운로드
연체 안내
FAQ
빠른 시작
콘솔 시작하기
COSBrowser 시작하기
사용자 가이드
요청 생성
버킷
객체
데이터 관리
일괄 프로세스
글로벌 가속
모니터링 및 알람
운영 센터
데이터 처리
스마트 툴 박스 사용 가이드
데이터 워크플로
애플리케이션 통합
툴 가이드
툴 개요
환경 설치 및 설정
COSBrowser 툴
COSCLI 툴
COSCMD 툴
COS Migration 툴
FTP Server 툴
Hadoop 툴
COSDistCp 툴
HDFS TO COS 툴
온라인 도구 (Onrain Dogu)
자가 진단 도구
실습 튜토리얼
개요
액세스 제어 및 권한 관리
성능 최적화
AWS S3 SDK를 사용하여 COS에 액세스하기
데이터 재해 복구 백업
도메인 관리 사례
이미지 처리 사례
COS 오디오/비디오 플레이어 사례
데이터 다이렉트 업로드
데이터 보안
데이터 검증
빅 데이터 사례
COS 비용 최적화 솔루션
3rd party 애플리케이션에서 COS 사용
마이그레이션 가이드
로컬 데이터 COS로 마이그레이션
타사 클라우드 스토리지 데이터를 COS로 마이그레이션
URL이 소스 주소인 데이터를 COS로 마이그레이션
COS 간 데이터 마이그레이션
Hadoop 파일 시스템과 COS 간 데이터 마이그레이션
데이터 레이크 스토리지
클라우드 네이티브 데이터 레이크
메타데이터 가속
데이터 레이크 가속기 GooseFS
데이터 처리
데이터 처리 개요
이미지 처리
미디어 처리
콘텐츠 조정
파일 처리
문서 미리보기
장애 처리
RequestId 가져오기
공용 네트워크로 COS에 파일 업로드 시 속도가 느린 문제
COS 액세스 시 403 에러 코드 반환
리소스 액세스 오류
POST Object 자주 발생하는 오류
보안 및 컴플라이언스
데이터 재해 복구
데이터 보안
액세스 관리
자주 묻는 질문
인기 질문
일반 문제
과금
도메인 규정 준수 문제
버킷 설정 문제
도메인 및 CDN 문제
파일 작업 문제
로그 모니터링 문제
권한 관리
데이터 처리 문제
데이터 보안 문제
사전 서명 URL 관련 문제
SDK FAQ
툴 관련 문제
API 관련 문제
Agreements
Service Level Agreement
개인 정보 보호 정책
데이터 처리 및 보안 계약
연락처
용어집
문서Cloud Object Storage

Deleting Objects

포커스 모드
폰트 크기
마지막 업데이트 시간: 2024-02-02 16:24:05

Overview

This document provides an overview of APIs and SDK code samples for deleting an object.
API
Operation
Description
Deleting an object
Deletes an object from a bucket.
Deleting multiple objects
Deletes multiple objects from a bucket in a single request

Simple Operations

Requests for simple operations need to be initiated through COSClient instances. You need to create a COSClient instance before performing simple operations.
COSClient instances are concurrency-safe. You are advised to create only one COSClient instance for a process and then close it when it is no longer used to initiate requests.

Creating a COSClient instance

Before calling the COS API, first create a COSClient instance.
// Create a COSClient instance, which is used to initiate requests later.
COSClient createCOSClient() {
// Set the user identity information.
// Log in to the [CAM console](https://console.tencentcloud.com/cam/capi) to view and manage the `SecretId` and `SecretKey` of your project.
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.
SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

// `ClientConfig` contains the COS client configuration for subsequent COS requests.
ClientConfig clientConfig = new ClientConfig();

// Set the bucket region.
// For more information on COS regions, visit https://www.tencentcloud.com/document/product/436/6224?from_cn_redirect=1.
clientConfig.setRegion(new Region("COS_REGION"));

// Set the request protocol to `HTTP` or `HTTPS`.
// For v5.6.53 or earlier, HTTPS is recommended.
// For v5.6.54 or later, HTTPS is used by default.
clientConfig.setHttpProtocol(HttpProtocol.https);

// The following settings are optional.

// Set the read timeout period, which is 30s by default.
clientConfig.setSocketTimeout(30*1000);
// Set the connection timeout period, which is 30s by default.
clientConfig.setConnectionTimeout(30*1000);

// If necessary, set the HTTP proxy, IP, and port.
clientConfig.setHttpProxyIp("httpProxyIp");
clientConfig.setHttpProxyPort(80);

// Generate a COS client.
return new COSClient(cred, clientConfig);
}

Creating a COSClient instance with a temporary key

If you want to request COS with a temporary key, you need to create a COSClient instance with the temporary key. This SDK does not generate temporary keys. For details on how to generate a temporary key, see Generating and Using Temporary Keys.

// Create a COSClient instance, which is used to initiate requests later.
COSClient createCOSClient() {
// Here, the temporary key information is needed.
// For details on how to generate temporary keys, visit https://www.tencentcloud.com/document/product/436/14048.
String tmpSecretId = "TMPSECRETID";
String tmpSecretKey = "TMPSECRETKEY";
String sessionToken = "SESSIONTOKEN";

COSCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);

// `ClientConfig` contains the COS client configuration for subsequent COS requests.
ClientConfig clientConfig = new ClientConfig();

// Set the bucket region.
// For more information on COS regions, visit https://www.tencentcloud.com/document/product/436/6224?from_cn_redirect=1.
clientConfig.setRegion(new Region("COS_REGION"));

// Set the request protocol to `HTTP` or `HTTPS`.
// For v5.6.53 or earlier, HTTPS is recommended.
// For v5.6.54 or later, HTTPS is used by default.
clientConfig.setHttpProtocol(HttpProtocol.https);

// The following settings are optional.

// Set the read timeout period, which is 30s by default.
clientConfig.setSocketTimeout(30*1000);
// Set the connection timeout period, which is 30s by default.
clientConfig.setConnectionTimeout(30*1000);

// If necessary, set the HTTP proxy, IP, and port.
clientConfig.setHttpProxyIp("httpProxyIp");
clientConfig.setHttpProxyPort(80);

// Generate a COS client.
return new COSClient(cred, clientConfig);
}

Deleting an object

This API (DELETE Object) is used to delete a specified object.

Method prototype

public void deleteObject(String bucketName, String key)
throws CosClientException, CosServiceException;

Sample request

// Before using the COS API, ensure that the process contains a COSClient instance. If such an instance does not exist, create one.
// For the detailed code, see "Simple Operations -> Creating a COSClient instance" on the current page.
COSClient cosClient = createCOSClient();

// Enter the bucket name in the format of `BucketName-APPID`.
String bucketName = "examplebucket-1250000000";
// Object key, the unique ID of an object in a bucket. For more information, see [Object Key](https://www.tencentcloud.com/document/product/436/13324).
String key = "exampleobject";

try {
cosClient.deleteObject(bucketName, key);
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
}

// After confirming that the process does not use the COSClient instance anymore, close it.
cosClient.shutdown();

Field description

Parameter
Description
Type
bucketName
Bucket name in the format of BucketName-APPID. For details, see the bucket naming conventions section in Bucket Overview.
String
key
Object key, the unique identifier of an object in a bucket. For example, in the object endpoint examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/do/picture.jpg, the object key is doc/picture.jpg. For details, see ObjectKey
String

Response description

Success: No value is returned.
Failure: If an error (such as authentication failure) occurs, the CosClientException or CosServiceException exception will be reported. For more information, see Troubleshooting.

Delete objects in batch

This API (DELETE Multiple Objects) is used to delete a batch of objects.

Method prototype

public DeleteObjectsResult deleteObjects(DeleteObjectsRequest deleteObjectsRequest)
throws MultiObjectDeleteException, CosClientException, CosServiceException;

Sample request

// Before using the COS API, ensure that the process contains a COSClient instance. If such an instance does not exist, create one.
// For the detailed code, see "Simple Operations -> Creating a COSClient instance" on the current page.
COSClient cosClient = createCOSClient();

// Enter the bucket name in the format of `BucketName-APPID`.
String bucketName = "examplebucket-1250000000";

DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);
// Set the list of keys to be deleted. A maximum of 1,000 keys can be deleted at a time.
ArrayList<KeyVersion> keyList = new ArrayList<>();
// Pass the names of files to be deleted.
// Note that filenames are not allowed to start with a forward slash (/) or backslash (\\). For example:
// The bucket directory contains the `a/b/c.txt` file. If you want to delete the `a/b/c.txt` file, run `keyList.add(new KeyVersion("a/b/c.txt"))`. If you run `keyList.add(new KeyVersion("/a/b/c.txt"))`, the deletion fails.
keyList.add(new KeyVersion("aaa"));
keyList.add(new KeyVersion("bbb"));
keyList.add(new KeyVersion("ccc"));
deleteObjectsRequest.setKeys(keyList);

try {
DeleteObjectsResult deleteObjectsResult = cosClient.deleteObjects(deleteObjectsRequest);
List<DeletedObject> deleteObjectResultArray = deleteObjectsResult.getDeletedObjects();
} catch (MultiObjectDeleteException mde) {
// If the deletion fails partially, `MultiObjectDeleteException` is returned.
List<DeletedObject> deleteObjects = mde.getDeletedObjects();
List<DeleteError> deleteErrors = mde.getErrors();
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
}

// After confirming that the process does not use the COSClient instance anymore, close it.
cosClient.shutdown();

Field description

Parameter
Description
Type
deleteObjectsRequest
Request
DeleteObjectsRequest
Description of the Request member:
Parameter
Description
Type
bucketName
Bucket naming format is BucketName-APPID. For details, see Naming Conventions
String
quiet
Indicates how to return the deletion result. Valid values: true and false (default). If set to true, only error messages due to failed deletions are returned. If set to false, messages indicating successful and failed deletion are returned
Boolean
keys
List of object paths. The version ID of each object is optional.
List<DeleteObjectsRequest.KeyVersion>
DeleteObjectsRequest.KeyVersion members are described as follows:
Parameter
Description
Type
key
Unique identifier of the object in the bucket. For example, in the object's access endpoint examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/do/picture.jpg, the object key is doc/picture.jpg. For more information, see Object Key.
String
version
(Optional) Specifies the version ID of an object to delete from a versioning-enabled bucket
String

Response description

Success: No value is returned.
Failure: an error (such as authentication failure) occurs, throwing the "CosClientException" or "CosServiceException" exception. For more information, see Troubleshooting.

Deleting objects of a specified version in batches

This API (DELETE Multiple Objects) is used to delete a batch of objects of a specified version.
Note:
Versioning must be enabled for the corresponding bucket.

Method prototype

public DeleteObjectsResult deleteObjects(DeleteObjectsRequest deleteObjectsRequest)
throws MultiObjectDeleteException, CosClientException, CosServiceException;

Sample request

// Before using the COS API, ensure that the process contains a COSClient instance. If such an instance does not exist, create one.
// For the detailed code, see "Simple Operations -> Creating a COSClient instance" on the current page.
COSClient cosClient = createCOSClient();

// Enter the bucket name in the format of `BucketName-APPID`.
String bucketName = "examplebucket-1250000000";

DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);
// Set the list of keys to be deleted. A maximum of 1,000 keys can be deleted at a time.
ArrayList<KeyVersion> keyList = new ArrayList<>();
// Enter the name of the file to delete and the corresponding version number.
// You can obtain the version number at: Listing Objects -> Simple Operations -> Listing the historical versions of an object.
keyList.add(new KeyVersion("aaa", "aaa versionId"));
keyList.add(new KeyVersion("bbb", "bbb versionId"));
keyList.add(new KeyVersion("ccc", "ccc versionId"));
deleteObjectsRequest.setKeys(keyList);

try {
DeleteObjectsResult deleteObjectsResult = cosClient.deleteObjects(deleteObjectsRequest);
List<DeletedObject> deleteObjectResultArray = deleteObjectsResult.getDeletedObjects();
} catch (MultiObjectDeleteException mde) {
// If the deletion fails partially, `MultiObjectDeleteException` is returned.
List<DeletedObject> deleteObjects = mde.getDeletedObjects();
List<DeleteError> deleteErrors = mde.getErrors();
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
}

// After confirming that the process does not use the COSClient instance anymore, close it.
cosClient.shutdown();

Field description

Parameter
Description
Type
deleteObjectsRequest
Request
DeleteObjectsRequest
Description of the Request member:
Parameter
Description
Type
bucketName
Bucket naming format is BucketName-APPID. For details, see Naming Conventions
String
quiet
Indicates how to return the deletion result. Valid values: true and false (default). If set to true, only error messages due to failed deletions are returned. If set to false, messages indicating successful and failed deletion are returned
Boolean
keys
List of object paths. The version ID of each object is optional.
List<DeleteObjectsRequest.KeyVersion>
DeleteObjectsRequest.KeyVersion members are described as follows:
Parameter
Description
Type
key
Unique identifier of the object in the bucket. For example, in the object's access endpoint examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/do/picture.jpg, the object key is doc/picture.jpg. For more information, see Object Key.
String
version
(Optional) Specifies the version ID of an object to delete from a versioning-enabled bucket
String

Response description

Success: No value is returned.
Failure: an error (such as authentication failure) occurs, throwing the "CosClientException" or "CosServiceException" exception. For more information, see Troubleshooting.

Deleting a directory

The directory deletion operation consists of two steps: list all objects in the directory to be deleted, and delete the objects in batches.
// For details about how to list all objects in a directory, see: Listing Objects -> Simple Operations -> Listing objects and subdirectories in a directory.
// For details about how to implement batch deletion, see "Deleting objects in batches" on the current page.

// Before using the COS API, ensure that the process contains a COSClient instance. If such an instance does not exist, create one.
// For the detailed code, see "Simple Operations -> Creating a COSClient instance" on the current page.
COSClient cosClient = createCOSClient();

// Enter the bucket name in the format of `BucketName-APPID`.
String bucketName = "examplebucket-1250000000";

// Directory to be deleted, which is a path relative to `bucket`.
String delDir = "exampledir";

ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// Set the bucket name
listObjectsRequest.setBucketName(bucketName);
// `prefix` indicates to use `prefix` as the prefix of objected listed.
// Here, enter the path of the listed directory relative to `bucket`.
listObjectsRequest.setPrefix(delDir);
// Set the maximum number of objects to be traversed, which can be up to 1,000 in one listobject operation
listObjectsRequest.setMaxKeys(1000);

// Save each list result.
ObjectListing objectListing = null;

do {
try {
objectListing = cosClient.listObjects(listObjectsRequest);
} catch (CosServiceException e) {
e.printStackTrace();
return;
} catch (CosClientException e) {
e.printStackTrace();
return;
}

// Save the list of listed objects.
List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();

ArrayList<KeyVersion> delObjects = new ArrayList<KeyVersion>();

for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
delObjects.add(new KeyVersion(cosObjectSummary.getKey()));
}

DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);

deleteObjectsRequest.setKeys(delObjects);

try {
DeleteObjectsResult deleteObjectsResult = cosClient.deleteObjects(deleteObjectsRequest);
List<DeletedObject> deleteObjectResultArray = deleteObjectsResult.getDeletedObjects();
} catch (MultiObjectDeleteException mde) {
// If the deletion fails partially, `MultiObjectDeleteException` is returned.
List<DeletedObject> deleteObjects = mde.getDeletedObjects();
List<DeleteError> deleteErrors = mde.getErrors();
} catch (CosServiceException e) {
e.printStackTrace();
return;
} catch (CosClientException e) {
e.printStackTrace();
return;
}

// Next start position.
String nextMarker = objectListing.getNextMarker();
listObjectsRequest.setMarker(nextMarker);
} while (objectListing.isTruncated());


도움말 및 지원

문제 해결에 도움이 되었나요?

피드백