Object Storage Service (OSS) uses a flat structure instead of a hierarchical structure which is used by traditional file systems to store objects. All data in OSS is stored as objects in buckets. You can use directories in OSS to help you categorize objects and control access to your objects in a simplified manner.
Structure
examplebucket
└── log/
├── date1.txt
├── date2.txt
├── date3.txt
└── destfolder/
└── 2021/
├── photo.jpg
- 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.
Access control based on directories
- 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. Technical support personnel need 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 your OSS resources. For more information, see Configure bucket policies to authorize other users to access OSS resources.
- An object named destfolder/2021/photo.jpg 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 ACL.
Create a directory
You can use one of the following methods to create a directory.
Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- On the Objects page, click Create Folder.
- In the Create Folder panel, configure the Folder Name parameter. The directory name must meet the following naming conventions:
- 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 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.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";
// 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.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket.
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, accessKeyId, accessKeySecret);
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: 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;
// 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.
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// 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 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 information about the uploaded string. For example, you can set the object access control list (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',
// 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.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret'
// Specify the name of the bucket.
bucket: 'examplebucket',
});
async function putBuffer () {
try {
// Specify the name of the directory. The directory 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
# 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.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# 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, 'yourEndpoint', 'examplebucket')
# Specify the name of the directory. The directory must end with a forward slash (/).
bucket.put_object('exampledir/', '')
package main
import (
"fmt"
"os"
"bytes"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
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. 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 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";
// 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.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the name of the directory. The directory 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 a 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";
/* 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. */
const char *access_key_id = "yourAccessKeyId";
const char *access_key_secret = "yourAccessKeySecret";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the name of the directory. The directory 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);
aos_str_set(&options->config->access_key_id, access_key_id);
aos_str_set(&options->config->access_key_secret, 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 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 indicates that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize oss_client_options. */
init_options(oss_client_options);
/* Initialize the parameters. */
aos_string_t bucket;
aos_string_t object;
aos_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 memory resources that are allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
Use ossutil
For more information about how to create a directory by using ossutil, 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 the directory.
Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- Rename or move a directory.
Scenario Procedure Rename a directory Move the pointer over the name of the directory that you want to rename and click the icon to rename the directory. The directory name cannot start with a forward slash (/).
Move a directory You can move a directory in a similar manner in which you rename a directory. However, you must add a forward slash (/) to the new name of the directory. The following examples show how to move a directory: - A subdirectory named subdir is located in a directory named destdir. To move subdir to another directory named destfolder, set the new directory name to /destfolder/subdir.
- A subdirectory named subdir is located in a directory named destdir. To move subdir to the root directory of the current bucket, set the new directory name to /subdir.
Use OSS SDKs
You can rename a directory only by using the OSS SDK for Java. The OSS SDK for Java must be 3.12.0 or later.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
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";
// 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.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket.
String bucketName = "examplebucket";
// Specify the absolute path of the source directory. The absolute path of the directory cannot contain the bucket name.
String sourceDir = "exampledir";
// Specify the absolute path of the destination directory that is in the same bucket as the source directory. The absolute path of the directory cannot contain the bucket name.
String destinationDir = "newexampledir";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
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 by using the OSS console, OSS SDKs, ossbrowser, and ossutil.
Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- On the Objects page, delete the specific directory. Important Do not refresh or close the Task List panel when you delete directories. Otherwise, the tasks are interrupted.
- Delete a directory from a bucket for which the hierarchical namespace feature is enabled
Click Permanently Delete in the Actions column of the directory that you want to delete. In the message that appears, click OK.
The directory and the objects in the directory are permanently deleted.
- Delete a directory from a bucket for which the hierarchical namespace feature is disabled
If the hierarchical namespace and versioning features are disabled for a 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 Display Previous Versions to Hide.
- Click Delete in the Actions column of the directory that you want to delete. In the massage 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 previous versions, see Restore a previous version.
- Permanently delete the directory
- In the upper-right corner of the object list, set Display Previous Versions to Show.
- Click Permanently Delete in the Actions column of the directory that you want to delete. In the message that appears, click OK.
The directory and the objects in the directory are permanently deleted.
- Store the deleted directory as a previous version
- Delete a directory from a bucket for which the hierarchical namespace feature is enabled
- In the Task List panel, you can view the deletion progress. When OSS performs deletion tasks, you can perform the following operations:
- Click Removed to remove the completed tasks from Task List.
- Click Pause All to pause all running tasks. When tasks are paused, you can perform the following operations:
- Click Start on the right side of a task to resume the task.
- Click Remove on the right side of a task 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 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.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";
// 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.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket.
String bucketName = "examplebucket";
// Specify the absolute path of the directory. The absolute path of the directory cannot contain the bucket name.
String directoryName = "exampledir";
// Specify the full path of the directory that you want to delete. The full path of the directory cannot contain the bucket name.
final String prefix = "log/";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Method 1: Use the deleteDirectory recursive deletion method to delete directories. 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 part of directories and objects are returned, the server returns nextDeleteToken. You can use nextDeleteToken to continue deleting remaining data.
// nextDeleteToken helps the server find the object or directory after which the 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 traverse deletion method to 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;
// 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.
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// 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. The full path of the directory cannot contain the bucket name.
OssClient::OSS_PREFIX => "log/",
);
$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 stored 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',
// 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.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Specify the name of the bucket.
bucket: 'examplebucket',
});
// 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.
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 stored in the directory.
deletePrefix('log/')
# -*- coding: utf-8 -*-
import oss2
# 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.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# 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')
# Specify the full path of the directory that you want to delete. The full path of the directory cannot contain the bucket name.
prefix = "log/"
# Delete the directory and all objects stored 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() {
// 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("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. The full path of the directory cannot contain the bucket name.
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 stored in the directory.
// Set oss.DeleteObjectsQuiet to true, which indicates that the list of deleted objects is not returned.
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 the information about the account that is used to access OSS. */
/* 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. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* 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. The full path of the directory cannot contain the bucket name. */
std::string keyPrefix = "log/";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, 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 stored 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 specify the name of the directory that you want to delete by using the prefix option in the rm command. For more information, see Delete objects.
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.