O OSS oferece diretórios que simulam uma estrutura de pastas. Isso facilita organizar, localizar e executar operações em lote com um grande volume de objetos.
Como funciona
O OSS utiliza armazenamento plano e não possui pastas reais. O console gera os diretórios a partir do delimitador / nos nomes dos objetos.
Por exemplo, ao visualizar a seguinte hierarquia no console:
examplebucket
└── log/
├── date1.txt
├── date2.txt
├── date3.txt
└── destfolder/
└── 2021/
├── photo.jpg
Os objetos reais armazenados no OSS são:
log/date1.txt
log/date2.txt
destfolder/2021/photo.jpg
Criar um diretório
Crie um diretório das seguintes formas:
Criação automática: Ao fazer upload de um objeto cujo nome contém um caminho, o sistema cria o diretório correspondente automaticamente.
-
Criação manual: Cria um objeto de zero byte com terminação
/para servir como marcador de diretório.Console
Faça logon no console do OSS. No bucket de destino, acesse Object Management > Objects.
Clique em Create Directory.
-
Insira um Directory Name e clique em OK.
Os nomes de diretório devem seguir estas regras:
O nome do diretório deve ter codificação UTF-8 e não pode conter emojis.
As barras (
/) são usadas no nome do diretório para indicar subdiretórios. Use barras (/) no nome do diretório para criar uma estrutura de diretórios aninhados. O nome do diretório não pode começar com uma barra (/) ou uma barra invertida (\). O nome do diretório não pode conter barras consecutivas (//).O nome do subdiretório não pode ser dois pontos consecutivos (
..).O nome do diretório deve ter de 1 a 254 caracteres.
ossutil
Crie um diretório chamado
dir/no bucketexamplebucket:ossutil mkdir oss://examplebucket/dirSDK
Estes exemplos criam um diretório usando SDKs comuns. Outros SDKs estão abordados em Introduction to OSS SDKs.
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 { // Set the endpoint. The China (Hangzhou) region is used in this example. Specify the actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // For security, do not hard-code access credentials. Leaked credentials can compromise all your resources. This example uses an environment variable for credentials. Ensure it is configured before running. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the bucket name, for example, examplebucket. String bucketName = "examplebucket"; // Specify the directory name for Method 1. String dirName = "exampledir/"; // Specify the directory name for Method 2. String dirName2 = "exampledir1/"; // Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // Method 1: Create a directory by calling the createDirectory operation. Before you use this method, you must enable hierarchical namespace. 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\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. $provider = new EnvironmentVariableCredentialsProvider(); // Specify the endpoint for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region. $endpoint = "yourEndpoint"; // Specify the bucket name, for example, examplebucket. $bucket= "examplebucket"; // Specify the directory name. The name must end with a forward slash (/). $object = "exampledir/"; $content = ""; try{ $config = array( "provider" => $provider, "endpoint" => $endpoint, ); $ossClient = new OssClient($config); $ossClient->putObject($bucket, $object, $content); } catch(OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . "OK" . "\n"); // You can set headers when you upload an object, such as setting the access permission to private or specifying custom metadata. $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 = new OssClient($config); $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 where your bucket is located. For example, use 'oss-cn-hangzhou' for the China (Hangzhou) region. region: 'yourregion', // Obtain access credentials from environment variables. Before you run this example, 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 bucket name. bucket: 'examplebucket', }); async function putBuffer () { try { // Specify the directory name. The 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 this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider()) # Specify the endpoint for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region. # Specify the bucket name. bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket') # Specify the directory name. The name must end with a forward slash (/). bucket.put_object('exampledir/', '')using System.Text; using Aliyun.OSS; // Specify the endpoint for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region. var endpoint = "yourEndpoint"; // Obtain access credentials from environment variables. Before you run this example, 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 bucket name, for example, examplebucket. var bucketName = "examplebucket"; // Specify the directory name. The 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 for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region. */ const char *endpoint = "yourEndpoint"; /* Specify the bucket name, for example, examplebucket. */ const char *bucket_name = "examplebucket"; /* Specify the directory name. The 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); /* Initialize the aos_string_t type with a char* string. */ aos_str_set(&options->config->endpoint, endpoint); /* Obtain access credentials from environment variables. Before you run this example, 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 a CNAME is used. 0 indicates that no CNAME is used. */ options->config->is_cname = 0; /* Set 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 at program startup to initialize global resources, such as the network and memory. */ if (aos_http_io_initialize(NULL, 0) != AOSE_OK) { exit(1); } /* The memory pool (pool), which is equivalent to apr_pool_t, is used for memory management. It is implemented in the apr library. */ aos_pool_t *pool; /* Create a memory pool. The second parameter is NULL, which indicates that the memory pool does not inherit from another memory pool. */ aos_pool_create(&pool, NULL); /* Create and initialize options. This parameter includes global configuration information such as the endpoint, access_key_id, access_key_secret, is_cname, and curl. */ oss_request_options_t *oss_client_options; /* Allocate memory for options from the memory pool. */ oss_client_options = oss_request_options_create(pool); /* Initialize the client option oss_client_options. */ init_options(oss_client_options); /* Initialize 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 upload is successful. */ if (aos_status_is_ok(resp_status)) { printf("put object from buffer succeeded\n"); } else { printf("put object from buffer failed\n"); } /* Destroy the memory pool. This releases the memory allocated to resources during the request. */ aos_pool_destroy(pool); /* Release the previously allocated global resources. */ aos_http_io_deinitialize(); return 0; }
Renomear um diretório
Renomear um diretório não é uma operação atômica e envolve duas etapas:
Cópia: Copie recursivamente todos os objetos do diretório de origem para um novo diretório de destino.
Exclusão: Após confirmar que a operação de cópia foi bem-sucedida, exclua permanentemente o diretório de origem e todos os objetos dentro dele.
A renomeação copia e exclui todos os objetos do diretório. Em diretórios grandes, esse processo é demorado e gera custos significativos com chamadas de API e transferência de dados. Avalie o impacto com cuidado antes de prosseguir.
-
Se o namespace hierárquico estiver ativado no seu bucket, você pode renomear um diretório diretamente.
Console
Faça logon no console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.
No painel de navegação à esquerda, escolha Object Management > Objects.
-
Renomeie ou mova o diretório.
Exclua um diretório especificando seu nome na opção prefix do comando
ossutilrm. rm (delete)Cenário
Ações
Renomear um diretório
Passe o mouse sobre o diretório de destino e clique no ícone
para renomear o diretório. O nome do diretório não pode começar com uma barra /.Mover um diretório
Mover um diretório é semelhante a renomeá-lo, mas o novo nome do diretório deve começar com uma barra (/). Especifique o diretório de destino com base em um dos seguintes cenários:
-
Para mover o subdiretório subdir do diretório pai destdir para outro diretório pai destfolder, insira /destfolder/subdir como o novo nome do diretório.
-
Para mover o subdiretório subdir do diretório pai destdir para o diretório raiz do bucket, insira /subdir como o novo nome do diretório.
-
SDK
A renomeação de diretórios é compatível apenas com o Java SDK 3.12.0 ou posterior.
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 { // Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. String endPoint = "yourEndpoint"; // Avoid hard-coding access credentials, as leaked credentials can compromise your resources. This example obtains credentials from environment variables. Ensure the variables are configured before running the code. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the absolute path of the source directory. The absolute path cannot contain the bucket name. String sourceDir = "exampledir"; // Specify the absolute path of the destination directory, which must be in the same bucket as the source directory. The absolute path cannot contain the bucket name. String destinationDir = "newexampledir"; // Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endPoint, credentialsProvider); try { // Rename the source directory in the bucket to 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(); } } } }API
Para acesso direto à API REST, chame RenameObject. Isso requer o cálculo manual da assinatura da requisição.
-
Se o namespace hierárquico estiver desativado, você deve renomear um diretório listando todos os objetos nele, copiando-os para um novo prefixo e, em seguida, excluindo os objetos originais.
NotaPara copiar em lote um grande número de objetos, use o Data Online Migration. Para mais informações, consulte Migrate data between OSS buckets.
ossutil
Com o ossutil, execute manualmente as etapas de Cópia e Exclusão:
-
Copiar objetos: Use o comando cp (Copy objects) com a opção
--recursive (-r)para copiar todo o conteúdo do diretórioold-dir/para o diretórionew-dir/no bucketexamplebucket.ossutil cp oss://examplebucket/old-dir/ oss://examplebucket/new-dir/ -r -
(Opcional) Verificar a operação de cópia: Use o comando ls (List resources) para verificar o novo diretório e confirmar se todos os objetos foram copiados com sucesso.
ossutil ls oss://examplebucket/new-dir/ -
Excluir o diretório de origem: Após confirmar que a cópia foi bem-sucedida, use o comando rm (Delete objects) com a opção
--recursive (-r)para excluir o diretório de origemold-dir/.AvisoEsta operação exclui permanentemente o diretório
old-dir/e todos os objetos dentro dele. Esta ação não pode ser desfeita. Prossiga com cuidado.ossutil rm oss://examplebucket/old-dir/ -r
SDK
Renomear um diretório com um SDK requer a combinação destas chamadas de API:
API
Renomeie um diretório combinando estas chamadas de API:
Cópia: CopyObject
Listagem: ListObjectsV2 (GetBucketV2)
Exclusão: DeleteObject
-
Excluir um diretório
Excluir um diretório também exclui todos os seus subdiretórios e objetos. Prossiga com cuidado.
Console
Faça logon no console do OSS.
Acesse a página Object Management > Objects do bucket de destino.
Selecione o diretório que deseja excluir e clique em Permanently Delete na coluna Actions.
-
Na caixa de diálogo exibida, clique em OK.
ImportanteNão atualize ou feche a lista de tarefas durante a exclusão. Isso pode interromper a tarefa.
Ossutil
Exclua o diretório test/ do bucket examplebucket:
ossutil rm oss://examplebucket/test/ -r
SDK
Exclua um diretório e todos os seus objetos especificando um Prefix. Por exemplo, para excluir o diretório log do bucket examplebucket, defina Prefix como 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 {
// The endpoint for the China (Hangzhou) region is used as an example. Specify the endpoint for your bucket's region.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Avoid hard-coding access credentials in your code to prevent security risks from leaks. This example loads credentials from environment variables. Ensure these variables are configured before running the code.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the absolute path of the directory. The path cannot contain the bucket name.
String directoryName = "exampledir";
// Specify the full path of the directory to be deleted. The path cannot contain the bucket name.
final String prefix = "log/";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Method 1: Recursively delete the directory by calling the deleteDirectory operation. Before you use this method, you must enable the hierarchical namespace feature.
DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
deleteDirectoryRequest.setDeleteRecursive(true);
DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);
// View the deletion result.
// A maximum of 100 directories and objects can be deleted at a time. If the deletion is incomplete, the server returns a `nextDeleteToken`. Use this token to continue deleting the remaining items.
// The nextDeleteToken parameter specifies the starting point for the next deletion.
String nextDeleteToken = deleteDirectoryResult.getNextDeleteToken();
System.out.println("delete next token:" + nextDeleteToken);
// The absolute path of the deleted directory.
System.out.println("delete dir name :" + deleteDirectoryResult.getDirectoryName());
// The total number of objects and directories that are deleted in this operation.
System.out.println("delete number:" + deleteDirectoryResult.getDeleteNumber());
// Method 2: Delete the directory and all objects in it by iterating through the results returned by the listObjects operation.
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;
// This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Specify the endpoint for your bucket's region. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "your-endpoint";
// Specify the bucket name.
$bucket = "examplebucket";
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
$option = array(
OssClient::OSS_MARKER => null,
// Specify the full path of the directory to be deleted. The path cannot contain the bucket name.
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 it.
$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 where your bucket is located. For example, for the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the bucket name.
bucket: 'yourbucketname'
});
// Handle a failed request to prevent `promise.all` from being interrupted. Returns the failure reason and the name of the object that failed 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 in it.
deletePrefix('log/')# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set your endpoint to the endpoint of the region where your bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the bucket name.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
prefix = "exampledir/"
# Delete the directory and all objects in it.
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() {
// This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint for the region where your bucket is located. For example, the endpoint for the China (Hangzhou) region is `https://oss-cn-hangzhou.aliyuncs.com`. Replace this with the endpoint for your actual region.
client, err := oss.New("your-endpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the bucket name.
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 to be deleted. The path 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 in it.
// Set `oss.DeleteObjectsQuiet` to `true` to suppress the deletion results.
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 failed to delete:", 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 OSS account information. */
/* Specify the endpoint for the region where your bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "your-endpoint";
/* Specify the bucket name. */
std::string BucketName = "examplebucket";
/* Specify the full path of the directory to be deleted. The path cannot contain the bucket name. */
std::string keyPrefix = "log/";
/* Initialize resources, such as the network. */
InitializeSdk();
ClientConfiguration conf;
/* This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set. */
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 it. */
auto delResult = client.DeleteObject(request);
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
/* Release resources, such as the network. */
ShutdownSdk();
return 0;
}API
Para acesso direto à API REST, chame a operação DeleteObject. Isso requer o cálculo manual da assinatura da requisição.
Consultar a contagem e o tamanho dos objetos
Método 1: Listar objetos sob demanda
Este método é ideal para consultas sob demanda em diretórios com menos de 10.000 objetos.
No painel de navegação à esquerda do bucket de destino, escolha .
Clique em Statistics à direita do diretório de destino.
Método 2: Consultar periodicamente com um inventário de bucket
Mais indicado para consultas periódicas em diretórios com até dezenas de bilhões de objetos.
No painel de navegação à esquerda do bucket de destino, escolha .
Clique em Create Inventory. No painel Create Inventory, selecione um Inventory Storage Bucket. Para o conteúdo do inventário, selecione Object Size. Para a correspondência de prefixo, insira o nome do diretório (por exemplo,
random_files/). Mantenha os outros parâmetros nas configurações padrão.-
Visualize o relatório de inventário.
-
Na página Objects, localize o arquivo de relatório de inventário gerado no caminho /Destination Bucket/inventory-id/data/.
-
Baixe o arquivo de relatório de inventário para visualizar a contagem de objetos e o tamanho total do diretório.
No arquivo de relatório de inventário, a coluna A contém o nome do bucket, a coluna B lista o nome de cada objeto e a coluna C mostra o tamanho desse objeto.
-
A documentação bucket inventory aborda os detalhes de configuração.
Método 3: Executar consultas complexas com o MetaSearch
Projetado para cenários de consultas quase em tempo real que filtram por prefixo, hora ou tipo de objeto.
No painel de navegação à esquerda do bucket de destino, escolha .
-
Na página Data Indexing, clique em Enable Now, selecione MetaSearch e clique em Enable.
NotaAtivar o MetaSearch pode levar algum tempo, dependendo do número de objetos no bucket.
Defina Object Name para correspondência de prefixo, insira
random_files/como prefixo e mantenha os outros parâmetros nas configurações padrão.-
Configure o formato de saída.
Defina Object Sort Order como Default.
Para Data Aggregation, agregue Object Size por Sum.
-
Clique em Query Now. Os resultados mostram a contagem total de objetos e o tamanho total do diretório
random_files/.Os resultados da consulta mostram que, em Data Aggregation, a soma dos tamanhos dos arquivos é de 14,47 GB. Em Objects, cada arquivo tem 50 MB de tamanho, o tipo de upload é Normal, a classe de armazenamento é Standard e a lista de controle de acesso (ACL) é Inherited from bucket.
A documentação MetaSearch aborda as opções de configuração e consulta.
Considerações para produção
Controle de acesso
No OSS, o controle de acesso baseia-se na correspondência de prefixos de objetos, e não no próprio objeto de diretório.
Por exemplo, para conceder a um usuário acesso de somente leitura a todos os objetos no diretório logs/:
Incorreto: Definir permissões no objeto marcador
logs/de zero byte.Correto: Crie uma política do RAM onde o campo
Resourceesteja definido comoacs:oss:*:*:your-bucket-name/logs/*. Esta política corresponde a todos os objetos que começam com o prefixologs/, independentemente de o objeto marcadorlogs/existir.
Otimização de desempenho
Profundidade do diretório: Evite estruturas profundamente aninhadas, como
a/b/c/d/.../file.log, pois a lógica de filtragem para operações de lista pode degradar o desempenho.Renomeações em grande escala: Renomear um diretório com muitos objetos gera um alto volume de chamadas de API e aumenta significativamente os custos de tráfego. Evite essa prática no design do seu sistema.