Object Storage Service (OSS) uses a flat structure instead of a hierarchical structure that is used by traditional file systems to store data. All data in OSS are stored as objects in buckets. For convenience purposes, the OSS console displays objects whose names end with a forward slash (/) as directories that are similar to folders in file systems. You can use directories to hierarchically organize and group objects and facilitate access control.
Directory logic implementation
OSS uses zero-byte objects to simulate directories to support a folder-like structure. You specify the names of directories. For example, if you create a directory named log in a bucket, OSS creates a zero-byte object named log/.
Example directories
OSS treats objects whose names end with a forward slash (/) as directories. The following example shows the directory structure of a bucket named examplebucket:
examplebucket
└── log/
├── date1.txt
├── date2.txt
├── date3.txt
└── destfolder/
└── 2021/
├── photo.jpg
In the preceding structure:
The following objects have the log prefix in their names: log/date1.txt, log/date2.txt, and log/date3.txt. In the OSS console, a directory named log is displayed. Three objects named date1.txt, date2.txt, and date3.txt are stored in the directory.
The following object contains the destfolder prefix in its name: destfolder/2021/photo.jpg. In the OSS console, a directory named destfolder is displayed. 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 examplebucket described in the preceding section:
The following objects within the log directory store the OSS access logs of a user in the last 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 issues reported by the user, such as slow access and object upload failures. In this case, you can configure bucket policies to authorize other users 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 a group photo of all your employees that was taken on a 2021 spring outing. 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.
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, OSS automatically creates the exampledir directory.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management.
On the Objects page, click Create Directory.
In the Create Directory panel, configure the Directory Name parameter.
The directory name must meet the following naming rules:
- 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 about how to use ossbrowser, 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.
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;
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";
// We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. You need to configure environment variables before you run the sample code.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the name of the directory that you want to create by using Method 1.
String dirName = "exampledir/";
// Specify the name of the directory that you want to create by using Method 2.
String dirName2 = "exampledir1/";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
// Method 1: Call the CreateDirectory operation to create a directory. // Before you create the directory, enable the hierarchical namespace feature for the bucket.
ossClient.createDirectory(bucketName, dirName);
// Method 2: Create a directory by uploading an empty string.
ossClient.putObject(bucketName, dirName2, new ByteArrayInputStream("".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();
}
}
}
}
<?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\OssClient;
use OSS\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. Example: examplebucket.
$bucket= "examplebucket";
// Specify the name of the directory. The directory name must end with a forward slash (/).
$object = "exampledir/";
$content = "";
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$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 the information of 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{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->putObject($bucket, $object, $content, $options);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");
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: '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',
});
async function putBuffer () {
try {
// Specify the name of the directory. The directory name must end with a forward slash (/).
const result = await client.put('exampledir/', new Buffer(''));
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/', '')
package main
import (
"fmt"
"os"
"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 {
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. Example: examplebucket.
bucket, err := client.Bucket("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the directory. The directory name must end with a forward slash (/).
err = bucket.PutObject("exampledir/", bytes.NewReader([]byte("")))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the name of the directory. The directory name must end with a forward slash (/). */
const char *object_name = "exampledir/";
const char *object_content = "";
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 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);
}
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 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 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_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);
/* Check 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 the memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
Use ossutil
You can use ossutil to create a directory. For more information, see mkdir.
Use RESTful APIs
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
After the hierarchical namespace feature is enabled, you can rename a directory.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
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. 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.*;
public class Demo {
public static void main(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.
String endPoint = "yourEndpoint";
// We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. You need to configure environment variables before you run the sample code.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the absolute path of the source directory. Do not include the bucket name in the absolute path of the directory.
String sourceDir = "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 of the directory.
String destinationDir = "newexampledir";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endPoint, credentialsProvider);
try {
// Change the absolute path of the source directory to that of the destination directory.
RenameObjectRequest renameObjectRequest = new RenameObjectRequest(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 RESTful APIs
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.
Delete a directory
You can delete directories that you no longer need.
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.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
On the Objects page, delete the directory that you want to delete.
ImportantDo not refresh or close the Task List panel when you delete a directory. Otherwise, the deletion is interrupted.
If the bucket has the hierarchical namespace feature enabled
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 the bucket has the hierarchical namespace feature disabled
If the hierarchical namespace and versioning features are disabled for the bucket, a directory in the bucket is deleted in the same way as it is deleted when 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. In the message that appears, click OK.
The deleted directory and the objects in the directory are stored as previous versions that can be restored. For more information about how to restore 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.
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 the bucket is unversioned
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 the bucket is versioning-enabled or versioning-suspended
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. In the message that appears, click OK.
The deleted directory and the objects in the directory are stored as previous versions that can be restored. For more information about how to restore 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.
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, you can view 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 pause all running tasks. When tasks are paused, 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 from the task are retained.
Click Start All to resume all paused tasks.
Use ossbrowser
You can use ossbrowser to perform the same bucket-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 about how to use ossbrowser, 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 specific 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/.
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;
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";
// We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. You need to configure environment variables before you run the sample code.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the absolute path of the directory. Do not include the bucket name in the absolute path of the directory.
String directoryName = "exampledir";
// Specify the full path of the directory that you want to delete. Do not include the bucket name in the full path.
final String prefix = "log/";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Method 1: Use the deleteDirectory recursive delete method to delete a directory. Before you use this method to delete a directory, you must enable the hierarchical namespace feature.
DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
deleteDirectoryRequest.setDeleteRecursive(true);
DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);
// Display the deleted directory.
// 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.
String nextDeleteToken = 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: Use the listObjects method to traverse and delete the directory and all objects in the directory.
String nextMarker = null;
ObjectListing objectListing = null;
do {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName)
.withPrefix(prefix)
.withMarker(nextMarker);
objectListing = ossClient.listObjects(listObjectsRequest);
if (objectListing.getObjectSummaries().size() > 0) {
List<String> keys = new ArrayList<String>();
for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
System.out.println("key name: " + s.getKey());
keys.add(s.getKey());
}
DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url");
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
try {
for(String obj : deletedObjects) {
String deleteObj = URLDecoder.decode(obj, "UTF-8");
System.out.println(deleteObj);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
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();
}
}
}
}
<?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\OssClient;
use OSS\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 = new OssClient($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 ($delObjects as $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;
}
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: '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 fail to be deleted.
async function handleDel(name, options) {
try {
await client.delete(name);
} catch (error) {
error.failObjectName = name;
return error;
}
}
// Delete multiple objects at a time.
async function deletePrefix(prefix) {
const list = await client.list({
prefix: prefix,
});
list.objects = list.objects || [];
const result = await Promise.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"
)
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 {
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 := 0
for {
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)
}
if len(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>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. */
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 (const auto& 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();
return 0;
}
Use ossutil
In ossutil, you can delete a directory by specifying the name of the directory in the prefix option in the rm command. For more information, see rm.
Use RESTful APIs
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.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
On the Objects page, locate 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
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;
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 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.
String keyPrefix = "exampledir/object";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
ObjectListing objectListing = null;
do {
// By default, 100 objects or directories are listed at a time.
ListObjectsRequest request = new ListObjectsRequest(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.
private static long calculateFolderLength(OSS ossClient, String bucketName, String folder) {
long size = 0L;
ObjectListing objectListing = null;
do {
// The default value of MaxKeys is 100. The maximum value of MaxKeys is 1000.
ListObjectsRequest request = new ListObjectsRequest(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;
}
}
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';
}
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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";
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
// 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);
Python
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def CalculateFolderLength(bucket, folder):
length = 0
for 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.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. Example: examplebucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
for obj in oss2.ObjectIterator(bucket, delimiter='/'):
if obj.is_prefix(): # Determine that obj is a directory.
length = CalculateFolderLength(bucket, obj.key)
print('directory: ' + obj.key + ' length:' + str(length) + "Byte.")
else: # Determine that obj is an object instead of a directory.
print('file:' + obj.key + ' length:' + str(obj.size) + "Byte.")
Go
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// 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.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucket, err := client.Bucket("yourBucketName")
if err != nil {
HandleError(err)
os.Exit(-1)
}
// List the sizes of objects in the directory.
prefix := "test/"
marker := ""
for {
lsRes, err := bucket.ListObjects(oss.Prefix(prefix),oss.Marker(marker))
if err != nil {
HandleError(err)
os.Exit(-1)
}
for _,object := range lsRes.Objects{
fmt.Println("Objects",object.Key, "length",object.Size ,"Byte.")
}
if lsRes.IsTruncated {
marker = lsRes.NextMarker
prefix = lsRes.Prefix
}else{
break
}
}
}
Use ossutil
For more information about how to use ossutil to query the total size of objects in a specified directory, see Query the total size of the current versions of objects in the specified directory.
Use RESTful APIs
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).