This topic contains important information on necessary precautions. We recommend that you read this topic carefully before proceeding.
Object Storage Service (OSS) uses a flat structure instead of a hierarchical structure that is used by traditional file systems to store objects. All data in OSS is stored as objects in buckets. To facilitate object management, the OSS console displays objects whose names end with a forward slash (/) as directories. Directories are similar to folders in file systems. You can use directories to hierarchically organize and group objects and facilitate access control.
Working principle
OSS uses zero-byte objects to simulate directories to support a folder-like structure. When you create a directory in OSS, you specify a name for the directory. For example, if you create a directory named log in a bucket, OSS creates a zero-byte object named log/.
Sample directories
OSS treats objects whose names end with a forward slash (/) as directories. The following example shows the structure of a bucket named examplebucket:
The following three objects have the "log" prefix in their names: log/date1.txt, log/date2.txt, and log/date3.txt. A directory named log is displayed in the OSS console. Three objects named date1.txt, date2.txt, and date3.txt are stored in the directory.
The name of the following object contains the "destfolder" prefix: destfolder/2021/photo.jpg. A directory named destfolder is displayed in the OSS console. The directory contains a subdirectory named 2021. An object named photo.jpg is stored in the subdirectory.
Authorize access to directories
The following examples show how to grant third-party users different permissions to access the specified directories and objects in the examplebucket bucket described in the preceding section:
The following objects in the log directory store the OSS access logs of a user in the previous three days: log/date1.txt, log/date2.txt, and log/date3.txt. The technical support team needs to view the logs stored in the three objects to troubleshoot reported issues, such as slow access and object upload failures. In this case, you can configure bucket policies to grant other users the permissions to access the objects in the log directory. For more information, see Configure bucket policies to authorize other users to access OSS resources.
The destfolder/2021/photo.jpg object in examplebucket is an employee group photo that was taken on a spring outing in 2021. You want all your employees to have access to the object. In this case, you can set the access control list (ACL) of the object to public-read. For more information, see Object ACLs.
Create a directory
You can use the following methods to create a directory.
Note
In addition to separately creating a directory, you can have a directory automatically created by specifying an object name prefix when you upload an object. For example, if you specify exampledir/demo.txt as the path to which you want to upload data and the exampledir directory does not exist in the bucket, OSS automatically creates the exampledir directory.
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.
On the Objects page, click Create Directory.
In the Create Directory panel, configure the Directory Name parameter.
The directory name must meet the following requirements:
The directory name must be UTF-8 characters and cannot contain emoticons.
Forward slashes (/) are used in a directory name to indicate subdirectories. You can specify a directory name that contains multiple forward slashes (/) to create subdirectories in the directory. The directory name cannot start with a forward slash (/) or a backslash (\). The directory name cannot contain consecutive forward slashes (/).
The name of a subdirectory cannot be two consecutive periods (..).
The directory name must be 1 to 254 characters in length.
Click OK.
Use 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 create a directory. For more information, see Use ossbrowser.
Use OSS SDKs
The following sample code provides examples on how to create a directory by using OSS SDKs for common programming languages. For more information about how to create a directory by using OSS SDKs for other programming languages, see Overview.
Java
PHP
Node.js
Python
C#
C
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;
import java.io.ByteArrayInputStream;
publicclassDemo {
publicstaticvoidmain(String[] args)throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. Stringendpoint="https://oss-cn-hangzhou.aliyuncs.com";
// For security purposes, we recommend that you do not save access credentials in the project code. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. EnvironmentVariableCredentialsProvidercredentialsProvider= CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket. StringbucketName="examplebucket";
// Specify the name of the directory that you want to create by using Method 1. StringdirName="exampledir/";
// Specify the name of the directory that you want to create by using Method 2. StringdirName2="exampledir1/";
// Create an OSSClient instance. OSSossClient=newOSSClientBuilder().build(endpoint, credentialsProvider);
try {
// Method 1: Call the createDirectory operation to create a directory. Before you use this method to create a directory, you must enable the hierarchical namespace feature.
ossClient.createDirectory(bucketName, dirName);
// Method 2: Upload an empty string to create a directory.
ossClient.putObject(bucketName, dirName2, newByteArrayInputStream("".getBytes()));
} 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();
}
}
}
}
<?phpif (is_file(__DIR__ . '/../autoload.php')) {
require_once__DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once__DIR__ . '/../vendor/autoload.php';
}
useOSS\Credentials\EnvironmentVariableCredentialsProvider;
useOSS\OssClient;
useOSS\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 = newEnvironmentVariableCredentialsProvider();
// 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 name of the directory. The directory name must end with a forward slash (/). $object = "exampledir/";
$content = "";
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = newOssClient($config);
$ossClient->putObject($bucket, $object, $content);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");
// You can configure headers in upload requests to specify information about the uploaded string. For example, you can set the object ACL to private and configure the user metadata of the object. $options = array(
OssClient::OSS_HEADERS => array(
'x-oss-object-acl' => 'private',
'x-oss-meta-info' => 'your info'
),
);
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = newOssClient($config);
$ossClient->putObject($bucket, $object, $content, $options);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");
constOSS = require('ali-oss');
const client = newOSS({
// 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',
// 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// Specify the name of the bucket. bucket: 'examplebucket',
});
asyncfunctionputBuffer () {
try {
// Specify the name of the directory. The directory name must end with a forward slash (/). const result = await client.put('exampledir/', newBuffer(''));
console.log(result);
} catch (e) {
console.log(e);
}
}
putBuffer();
# -*- 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.ProviderAuth(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. # Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the name of the directory. The directory name must end with a forward slash (/).
bucket.put_object('exampledir/', '')
using System.Text;
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 name of the directory. The directory name must end with a forward slash (/). var objectName = "exampledir/";
var objectContent = "";
// Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
// Create the directory.
client.PutObject(bucketName, objectName, requestContent);
Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
#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. */constchar *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */constchar *bucket_name = "examplebucket";
/* Specify the name of the directory. The directory name must end with a forward slash (/). */constchar *object_name = "exampledir/";
constchar *object_content = "";
voidinit_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize aos_string_t. */
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 whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Configure network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
intmain(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 that is 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 specifies 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 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_list_t buffer;
aos_buf_t *content = NULL;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
aos_list_init(&buffer);
content = aos_buf_pack(oss_client_options->pool, object_content, strlen(object_content));
aos_list_add_tail(&content->node, &buffer);
/* Upload the object. */
resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object, &buffer, headers, &resp_headers);
/* Determine whether the object is uploaded. */if (aos_status_is_ok(resp_status)) {
printf("put object from buffer succeeded\n");
} else {
printf("put object from buffer failed\n");
}
/* Release the memory pool. This operation releases memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return0;
}
Use ossutil
You can use ossutil to create a directory. For more information, see mkdir.
Use the OSS API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutObject and CreateDirectory.
Rename a directory
If the hierarchical namespace feature is enabled for a bucket, you can directly rename a directory in the bucket.
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.
Rename or move a directory.
Operation
Procedure
Rename a directory
Move the pointer over the name of the directory that you want to rename, and click the icon. The directory name cannot start with a forward slash (/).
Move a directory
The steps to move a directory are similar to the steps to rename a directory. The difference is that you must add a forward slash (/) to the new name of the directory when you move a directory. The following examples show how to move a directory:
To move the subdir subdirectory from the destdir directory to the destfolder directory, set the new directory name to /destfolder/subdir.
To move the subdir subdirectory from the destdir directory to the root directory of the current bucket, set the new directory name to /subdir.
Use OSS SDKs
Among OSS SDKs for different programming languages, only OSS SDK for Java 3.12.0 and later support directory renaming. The following sample code provides an example on how to rename a directory by using OSS SDK for 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;
import com.aliyun.oss.model.*;
publicclassDemo {
publicstaticvoidmain(String[] args)throws Exception {
// 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. StringendPoint="yourEndpoint";
// For security purposes, we recommend that you do not save access credentials in the project code. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. EnvironmentVariableCredentialsProvidercredentialsProvider= CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket. StringbucketName="examplebucket";
// Specify the absolute path of the source directory. Do not include the bucket name in the absolute path. StringsourceDir="exampledir";
// Specify the absolute path of the destination directory that is in the same bucket as the source directory. Do not include the bucket name in the absolute path. StringdestinationDir="newexampledir";
// Create an OSSClient instance. OSSossClient=newOSSClientBuilder().build(endPoint, credentialsProvider);
try {
// Change the absolute path of the source directory to the path of the destination directory. RenameObjectRequestrenameObjectRequest=newRenameObjectRequest(bucketName, sourceDir, destinationDir);
ossClient.renameObject(renameObjectRequest);
} 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();
}
}
}
}
Use the OSS API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see Rename.
If the hierarchical namespace feature is not enabled for a bucket and you want to rename a directory in the bucket, you must list all objects in the bucket, copy the objects to a new directory, and delete the objects in the old directory.
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 rename a directory. For more information about how to use ossbrowser, see Use ossbrowser.
Use OSS SDKs
Several operations are involved when you use OSS SDKs to rename a directory. For code examples of using OSS SDKs to rename a directory, see List objects, Copy objects, and Delete objects.
Use ossutil
You can use ossutil to rename a directory. For more information about the ossutil commands involved in renaming a directory, see Is, Copy objects, and rm.
Use the OSS API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see ListObjectsV2 (GetBucketV2) or GetBucket(ListObjects), CopyObject, and DeleteObject.
Delete a directory
You can delete a directory that you no longer need.
Warning
If you delete a directory, the subdirectories and all objects in the directory are synchronously deleted. We recommend that you exercise caution when you delete a directory.
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.
On the Objects page, delete the desired directory.
Important
Do not refresh or close the Task List panel when you delete a directory. Otherwise, the deletion is interrupted.
If the hierarchical namespace feature is enabled for the bucket
Find the directory that you want to delete and click Delete in the Actions column. In the message that appears, click OK.
The directory and the objects in the directory are permanently deleted.
If the hierarchical namespace feature is disabled for the bucket
If the hierarchical namespace and versioning features are disabled for the bucket, you delete a directory from the bucket in the same way you delete a directory from a bucket for which the hierarchical namespace feature is enabled.
If the hierarchical namespace feature is disabled and the versioning feature is enabled for the bucket, you can delete the directory by using one of the following methods:
Store the deleted directory as a previous version
In the upper-right corner of the object list, set Previous Versions to Hide.
Find the directory that you want to delete and click Delete in the Actions column. In the message that appears, click OK.
The deleted directory and the objects in the directory are stored as previous versions that can be recovered. For more information about how to recover a previous version of an object, see Restore a previous version.
Permanently delete the directory
In the upper-right corner of the object list, set Previous Versions to Show.
Find the directory that you want to delete and click Permanently Delete in the Actions column. In the message that appears, click OK.
The directory and the objects in the directory are permanently deleted.
If versioning is disabled for the bucket
Find the directory that you want to delete and click Permanently Delete in the Actions column. In the message that appears, click OK.
The directory and the objects in the directory are permanently deleted.
If versioning is enabled or suspended for the bucket
Store the deleted directory as a previous version
In the upper-right corner of the object list, set Previous Versions to Hide.
Find the directory that you want to delete and click Delete in the Actions column. In the message that appears, click OK.
The deleted directory and the objects in the directory are stored as previous versions that can be recovered. For more information about how to recover a previous version of an object, see Restore a previous version.
Permanently delete the directory
In the upper-right corner of the object list, set Previous Versions to Show.
Find the directory that you want to delete and click Permanently Delete in the Actions column. In the message that appears, click OK.
The directory and the objects in the directory are permanently deleted.
In the Task List panel, check the deletion progress.
When OSS performs deletion tasks, you can perform the following operations:
Click Remove Completed Tasks to remove the completed tasks from Task List.
Click Suspend All to suspend all the running deletion tasks. When tasks are suspended, you can perform the following operations:
In the Actions column, click Start to resume the task.
In the Actions column, click Remove to remove the task. If you remove a task, the objects that are not deleted by the task are retained.
Click Start All to resume all the suspended tasks.
Use 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 a directory. For more information, see Use ossbrowser.
Use OSS SDKs
The following sample code provides examples on how to delete a directory by using OSS SDKs for common programming languages. For more information about how to delete a directory by using OSS SDKs for other programming languages, see Overview.
When you delete objects, you can specify a prefix that is contained in the names of all objects you want to delete. In this case, the directory whose name contains the specified prefix and all objects in the directory are deleted. For example, to delete the log directory and all objects in the directory from examplebucket, you can set the prefix to log/.
Java
PHP
Node.js
Python
Go
C++
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;
import com.aliyun.oss.model.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
publicclassDemo {
publicstaticvoidmain(String[] args)throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. Stringendpoint="https://oss-cn-hangzhou.aliyuncs.com";
// For security purposes, we recommend that you do not save access credentials in the project code. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. EnvironmentVariableCredentialsProvidercredentialsProvider= CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket. StringbucketName="examplebucket";
// Specify the absolute path of the directory. Do not include the bucket name in the absolute path. StringdirectoryName="exampledir";
// Specify the full path of the directory that you want to delete. Do not include the bucket name in the full path. finalStringprefix="log/";
// Create an OSSClient instance. OSSossClient=newOSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Method 1: Call deleteDirectory to recursively delete a directory. Before you use this method to delete a directory, you must enable the hierarchical namespace feature. DeleteDirectoryRequestdeleteDirectoryRequest=newDeleteDirectoryRequest(bucketName, directoryName);
deleteDirectoryRequest.setDeleteRecursive(true);
DeleteDirectoryResultdeleteDirectoryResult= ossClient.deleteDirectory(deleteDirectoryRequest);
// Display the deletion result. // You can delete up to 100 directories and objects at a time. If only a portion of directories and objects are deleted, the server returns nextDeleteToken. You can use nextDeleteToken to continue deleting the remaining data. // nextDeleteToken helps the server find the object or directory after which the next delete operation begins. StringnextDeleteToken= deleteDirectoryResult.getNextDeleteToken();
System.out.println("delete next token:" + nextDeleteToken);
// Display the absolute path of the deleted directory.
System.out.println("delete dir name :" + deleteDirectoryResult.getDirectoryName());
// Display the total number of deleted objects and directories.
System.out.println("delete number:" + deleteDirectoryResult.getDeleteNumber());
// Method 2: Call listObjects to traverse and delete the directory and all objects in the directory. StringnextMarker=null;
ObjectListingobjectListing=null;
do {
ListObjectsRequestlistObjectsRequest=newListObjectsRequest(bucketName)
.withPrefix(prefix)
.withMarker(nextMarker);
objectListing = ossClient.listObjects(listObjectsRequest);
if (objectListing.getObjectSummaries().size() > 0) {
List<String> keys = newArrayList<String>();
for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
System.out.println("key name: " + s.getKey());
keys.add(s.getKey());
}
DeleteObjectsRequestdeleteObjectsRequest=newDeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url");
DeleteObjectsResultdeleteObjectsResult= ossClient.deleteObjects(deleteObjectsRequest);
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
try {
for(String obj : deletedObjects) {
StringdeleteObj= URLDecoder.decode(obj, "UTF-8");
System.out.println(deleteObj);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
nextMarker = objectListing.getNextMarker();
} while (objectListing.isTruncated());
} 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();
}
}
}
}
<?phpif (is_file(__DIR__ . '/../autoload.php')) {
require_once__DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once__DIR__ . '/../vendor/autoload.php';
}
useOSS\OssClient;
useOSS\Core\OssException;
// 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 = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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. $bucket = "examplebucket";
try {
$ossClient = newOssClient($accessKeyId, $accessKeySecret, $endpoint, false);
$option = array(
OssClient::OSS_MARKER => null,
// Specify the full path of the directory that you want to delete. Do not include the bucket name in the full path. OssClient::OSS_PREFIX => "log/",
OssClient::OSS_DELIMITER=>'',
);
$bool = true;
while ($bool){
$result = $ossClient->listObjects($bucket,$option);
$objects = array();
if(count($result->getObjectList()) > 0){
foreach ($result->getObjectList() as$key => $info){
printf("key name:".$info->getKey().PHP_EOL);
$objects[] = $info->getKey();
}
// Delete the directory and all objects in the directory. $delObjects = $ossClient->deleteObjects($bucket, $objects);
foreach ($delObjectsas$info){
$obj = strval($info);
printf("Delete ".$obj." : Success" . PHP_EOL);
}
}
if($result->getIsTruncated() === 'true'){
$option[OssClient::OSS_MARKER] = $result->getNextMarker();
}else{
$bool = false;
}
}
printf("Delete Objects : OK" . PHP_EOL);
} catch (OssException $e) {
printf("Delete Objects : Failed" . PHP_EOL);
printf($e->getMessage() . PHP_EOL);
return;
}
constOSS = require('ali-oss');
const client = newOSS({
// 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',
// 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,
// Specify the name of the bucket. bucket: 'yourbucketname'
});
// Handle request failures, prevent the interruption of promise.all, and return failure causes and the names of objects that failed to be deleted. asyncfunctionhandleDel(name, options) {
try {
await client.delete(name);
} catch (error) {
error.failObjectName = name;
return error;
}
}
// Delete multiple objects at a time. asyncfunctiondeletePrefix(prefix) {
const list = await client.list({
prefix: prefix,
});
list.objects = list.objects || [];
const result = awaitPromise.all(list.objects.map((v) =>handleDel(v.name)));
console.log(result);
}
// Delete the directory and all objects in the directory. deletePrefix('log/')
# -*- 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.ProviderAuth(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. # Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
prefix = "exampledir/"# Delete the directory and all objects in the directory. for obj in oss2.ObjectIterator(bucket, prefix=prefix):
bucket.delete_object(obj.key)
package main
import (
"fmt""os""github.com/aliyun/aliyun-oss-go-sdk/oss"
)
funcmain() {
// 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 {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 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.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucket, err := client.Bucket("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
marker := oss.Marker("")
// Specify the full path of the directory that you want to delete. Do not include the bucket name in the full path.
prefix := oss.Prefix("log/")
count := 0for {
lor, err := bucket.ListObjects(marker, prefix)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
objects := []string{}
for _, object := range lor.Objects {
objects = append(objects, object.Key)
}
// Delete the directory and all objects in the directory. // Set the oss.DeleteObjectsQuiet parameter to true. This setting indicates that OSS does not return a message after objects are deleted.
delRes, err := bucket.DeleteObjects(objects, oss.DeleteObjectsQuiet(true))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
iflen(delRes.DeletedObjects) > 0 {
fmt.Println("these objects deleted failure,", delRes.DeletedObjects)
os.Exit(-1)
}
count += len(objects)
prefix = oss.Prefix(lor.Prefix)
marker = oss.Marker(lor.NextMarker)
if !lor.IsTruncated {
break
}
}
fmt.Printf("success,total delete object count:%d\n", count)
}
#include<alibabacloud/oss/OssClient.h>usingnamespace AlibabaCloud::OSS;
intmain(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. */
std::string BucketName = "examplebucket";
/* Specify the full path of the directory that you want to delete. Do not include the bucket name in the full path. */
std::string keyPrefix = "log/";
/* 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);
std::string nextMarker = "";
bool isTruncated = false;
do {
ListObjectsRequest request(BucketName);
request.setPrefix(keyPrefix);
request.setMarker(nextMarker);
auto outcome = client.ListObjects(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "ListObjects fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
break;
}
for (constauto& object : outcome.result().ObjectSummarys()) {
DeleteObjectRequest request(BucketName, object.Key());
/* Delete the directory and all objects in the directory. */auto delResult = client.DeleteObject(request);
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
/* Release resources, such as network resources. */ShutdownSdk();
return0;
}
Use ossutil
In ossutil, you can delete a directory by specifying the name of the directory in the prefix option of the rm command. For more information, see rm.
Use the OSS API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see DeleteObject and DeleteDirectory.
Query the size of a directory
You can use several methods to query the total size of objects in a directory.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
On the Objects page, find the directory whose size you want to query and click the refresh icon in the Object Size column.
OSS displays the total size of the objects in the directory, as shown in the following example:
Use OSS SDKs
The following sample code provides examples on how to use OSS SDKs for common programming languages to query the size of a directory. For more information about how to use OSS SDKs for other programming languages to query the size of a directory, see Overview.
Java
PHP
Python
Go
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;
publicclassDemo {
publicstaticvoidmain(String[] args)throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. Stringendpoint="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. EnvironmentVariableCredentialsProvidercredentialsProvider= CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket. StringbucketName="examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. If you want to traverse the sizes of objects and directories in the root directory, leave this parameter empty. StringkeyPrefix="exampledir/object";
// 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. Stringregion="cn-hangzhou";
// Create an OSSClient instance. ClientBuilderConfigurationclientBuilderConfiguration=newClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSSossClient= OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build(););
try {
ObjectListingobjectListing=null;
do {
// By default, 100 objects or directories are listed at a time. ListObjectsRequestrequest=newListObjectsRequest(bucketName).withDelimiter("/").withPrefix(keyPrefix);
if (objectListing != null) {
request.setMarker(objectListing.getNextMarker());
}
objectListing = ossClient.listObjects(request);
List<String> folders = objectListing.getCommonPrefixes();
for (String folder : folders) {
System.out.println(folder + " : " + (calculateFolderLength(ossClient, bucketName, folder) / 1024) + "KB");
}
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println(s.getKey() + " : " + (s.getSize() / 1024) + "KB");
}
} while (objectListing.isTruncated());
} 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();
}
}
}
// List the sizes of objects in a specific directory in a bucket. privatestaticlongcalculateFolderLength(OSS ossClient, String bucketName, String folder) {
longsize=0L;
ObjectListingobjectListing=null;
do {
// The default value of MaxKeys is 100. The maximum value of MaxKeys is 1000. ListObjectsRequestrequest=newListObjectsRequest(bucketName).withPrefix(folder).withMaxKeys(1000);
if (objectListing != null) {
request.setMarker(objectListing.getNextMarker());
}
objectListing = ossClient.listObjects(request);
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
size += s.getSize();
}
} while (objectListing.isTruncated());
return size;
}
}
<?phpif (is_file(__DIR__ . '/../autoload.php')) {
require_once__DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once__DIR__ . '/../vendor/autoload.php';
}
require_once__DIR__ . '/Common.php';
useOSS\Credentials\EnvironmentVariableCredentialsProvider;
useOSS\OssClient;
useOSS\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 = newEnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. $bucket= "examplebucket";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = newOssClient($config);
// Set the directory name to fun/. $prefix = 'fun/';
$delimiter = '';
$nextMarker = '';
$maxkeys = 1000;
$options = array(
'delimiter' => $delimiter,
'prefix' => $prefix,
'max-keys' => $maxkeys,
'marker' => $nextMarker,
);
$bool = true;
$size = 0;
while ($bool){
$result = $ossClient->listObjects($bucket,$options);
foreach ($result->getObjectList() as$objInfo){
printf("object name".$objInfo->getKey().":" . ($objInfo->getSize() / 1024) . "KB".PHP_EOL);
$size+=$objInfo->getSize();
}
if($result->getIsTruncated() === 'true'){
$options['marker'] = $result->getNextMarker();
}else{
$bool = false;
}
}
printf($prefix.":" . ($size / 1024) . "KB".PHP_EOL);
# -*- coding: utf-8 -*-import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
defCalculateFolderLength(bucket, folder):
length = 0for obj in oss2.ObjectIterator(bucket, prefix=folder):
length += obj.size
return length
# 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, "yourBucketName", region=region)
for obj in oss2.ObjectIterator(bucket, delimiter='/'):
if obj.is_prefix(): # Specify the operation to perform if obj is determined as a directory.
length = CalculateFolderLength(bucket, obj.key)
print('directory: ' + obj.key + ' length:' + str(length) + "Byte.")
else: # Specify the operation to perform if obj is determined as an object. print('file:' + obj.key + ' length:' + str(obj.size) + "Byte.")
package main
import (
"log""github.com/aliyun/aliyun-oss-go-sdk/oss"
)
funcmain() {
// 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 your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket.
bucketName := "yourBucketName"// Replace yourBucketName with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List the sizes of the objects in a specific directory.
prefix := "test/"// Replace test/ with the actual directory name.
marker := ""for {
lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Display the listed objects and their sizes.for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Size: %d Byte(s)\n", object.Key, object.Size)
}
// If the returned results are truncated, update the value of the marker parameter to obtain the remaining results.if lsRes.IsTruncated {
marker = lsRes.NextMarker
} else {
break
}
}
log.Println("All objects have been listed with their sizes.")
}
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see GetBucket(ListObjects).