OSS proporciona directorios que simulan una estructura de carpetas. Esto facilita organizar, localizar y ejecutar operaciones masivas sobre grandes cantidades de objetos.
Cómo funciona
OSS utiliza un almacenamiento plano y no cuenta con carpetas reales. Los directorios en la consola se generan a partir del delimitador / presente en los nombres de los objetos.
Por ejemplo, cuando observa la siguiente jerarquía en la consola:
examplebucket
└── log/
├── date1.txt
├── date2.txt
├── date3.txt
└── destfolder/
└── 2021/
├── photo.jpg
Los objetos almacenados realmente en OSS son los siguientes:
log/date1.txt
log/date2.txt
destfolder/2021/photo.jpg
Creación de un directorio
Cree un directorio mediante cualquiera de los siguientes métodos:
Creación automática: al cargar un objeto cuyo nombre contiene una ruta, el directorio correspondiente se crea automáticamente.
-
Creación manual: este método genera un objeto de cero bytes que termina en
/y actúa como marcador de posición del directorio.Console
Inicie sesión en la consola de OSS. En el bucket de destino, vaya a Object Management > Objects.
Haga clic en Create Directory.
-
Introduzca un valor en Directory Name y haga clic en OK.
Los nombres de directorio deben cumplir las siguientes reglas:
El nombre del directorio debe estar codificado en UTF-8 y no puede contener emojis.
Las barras diagonales (
/) se utilizan en el nombre del directorio para indicar subdirectorios. Use barras diagonales (/) en el nombre del directorio para crear una estructura anidada. El nombre no puede comenzar con una barra diagonal (/) ni con una barra invertida (\). Tampoco puede contener barras diagonales consecutivas (//).El nombre del subdirectorio no puede consistir en dos puntos consecutivos (
..).El nombre del directorio debe tener entre 1 y 254 caracteres.
ossutil
Ejecute el siguiente comando para crear un directorio llamado
dir/en el bucketexamplebucket:ossutil mkdir oss://examplebucket/dirSDK
A continuación se muestra cómo crear un directorio con los SDK más comunes. Para otros SDK, consulte 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; }
Renombrar un directorio
La operación de renombrar un directorio no es atómica e implica dos pasos:
Copiar: copie de forma recursiva todos los objetos del directorio de origen hacia un nuevo directorio de destino.
Eliminar: después de confirmar que la copia finalizó correctamente, elimine permanentemente el directorio de origen y todos los objetos que contiene.
Al renombrar, se copian y eliminan todos los objetos del directorio. En directorios grandes, este proceso consume mucho tiempo y genera costos significativos por llamadas a la API y transferencia de datos. Evalúe cuidadosamente el impacto antes de continuar.
-
Si el espacio de nombres jerárquico está habilitado en su bucket, puede renombrar un directorio directamente.
Console
Inicie sesión en la consola de OSS.
En el panel de navegación izquierdo, haga clic en Buckets. En la página Buckets, busque el bucket deseado y haga clic en él.
En el panel de navegación izquierdo, elija Object Management > Objects.
-
Renombre o mueva el directorio.
Para eliminar un directorio, especifique su nombre en la opción prefix del comando
rmdeossutil. rm (delete)Escenario
Acciones
Renombrar un directorio
Coloque el cursor sobre el directorio de destino y haga clic en el ícono
para renombrarlo. El nombre del directorio no puede comenzar con una barra diagonal /.Mover un directorio
Mover un directorio es similar a renombrarlo, pero el nuevo nombre debe comenzar con una barra diagonal (/). Especifique el directorio de destino según uno de los siguientes escenarios:
-
Si desea mover el subdirectorio subdir del directorio principal destdir a otro directorio principal llamado destfolder, introduzca /destfolder/subdir como nuevo nombre.
-
Si desea mover el subdirectorio subdir del directorio principal destdir al directorio raíz del bucket, introduzca /subdir como nuevo nombre.
-
SDK
El cambio de nombre de directorios solo es compatible con Java SDK 3.12.0 o versiones posteriores.
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 acceder directamente a la API REST, llame a RenameObject. Este método requiere calcular manualmente la firma de la solicitud.
-
Si el espacio de nombres jerárquico está deshabilitado, debe renombrar el directorio mediante tres acciones: listar todos sus objetos, copiarlos a un nuevo prefijo y eliminar los objetos originales.
NotaPara copiar en lotes una gran cantidad de objetos, utilice Data Online Migration. Para obtener más información, consulte Migrate data between OSS buckets.
ossutil
Con ossutil, ejecute manualmente los pasos de copiar y eliminar:
-
Copiar objetos: utilice el comando cp (Copy objects) con la opción
--recursive (-r)para copiar todo el contenido del directorioold-dir/al directorionew-dir/dentro del bucketexamplebucket.ossutil cp oss://examplebucket/old-dir/ oss://examplebucket/new-dir/ -r -
(Opcional) Comprobar la copia: utilice el comando ls (List resources) para revisar el nuevo directorio y comprobar que todos los objetos se copiaron correctamente.
ossutil ls oss://examplebucket/new-dir/ -
Eliminar el directorio de origen: tras confirmar que la copia finalizó correctamente, utilice el comando rm (Delete objects) con la opción
--recursive (-r)para eliminar el directorio de origenold-dir/.AvisoEsta operación elimina permanentemente el directorio
old-dir/y todos los objetos que contiene. Esta acción no se puede deshacer. Proceda con precaución.ossutil rm oss://examplebucket/old-dir/ -r
SDK
Para renombrar un directorio con un SDK, combine las siguientes llamadas a la API:
API
Combine las siguientes llamadas a la API para renombrar un directorio:
Copiar: CopyObject
Listar: ListObjectsV2 (GetBucketV2)
Eliminar: DeleteObject
-
Eliminar un directorio
Al eliminar un directorio también se eliminan todos sus subdirectorios y objetos. Proceda con precaución.
Console
Inicie sesión en la consola de OSS.
Vaya a la página Object Management > Objects del bucket de destino.
Seleccione el directorio que desea eliminar y haga clic en Permanently Delete en la columna Actions.
-
En el cuadro de diálogo que aparece, haga clic en OK.
ImportanteNo actualice ni cierre la lista de tareas durante la eliminación, ya que esto podría interrumpir el proceso.
Ossutil
Elimine el directorio test/ del bucket examplebucket:
ossutil rm oss://examplebucket/test/ -r
SDK
Elimine un directorio y todos sus objetos al especificar un Prefix. Por ejemplo, para eliminar el directorio log del bucket examplebucket, establezca 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 acceder directamente mediante la API REST, llame a la operación DeleteObject. Esto requiere calcular manualmente la firma de la solicitud.
Consultar la cantidad y el tamaño de los objetos
Método 1: listar objetos bajo demanda
Este método es adecuado para consultas bajo demanda en directorios con menos de 10 000 objetos.
En el panel de navegación izquierdo del bucket de destino, elija .
Haga clic en Statistics a la derecha del directorio de destino.
Método 2: consultar periódicamente con un inventario de buckets
Recomendado cuando necesita ejecutar consultas periódicas en directorios con hasta decenas de miles de millones de objetos.
En el panel de navegación izquierdo del bucket de destino, elija .
Haga clic en Create Inventory. En el panel Create Inventory, seleccione un Inventory Storage Bucket. Para el contenido del inventario, seleccione Object Size. En la coincidencia de prefijos, introduzca el nombre del directorio (por ejemplo,
random_files/). Mantenga los demás parámetros con su configuración predeterminada.-
Consulte el informe de inventario.
-
En la página Objects, busque el archivo de informe de inventario generado en la ruta
/Destination Bucket/inventory-id/data/. -
Descargue el archivo de informe de inventario para ver la cantidad de objetos y el tamaño total del directorio.
En el archivo de informe de inventario, la columna A contiene el nombre del bucket, la columna B muestra el nombre de cada objeto y la columna C indica el tamaño de dicho objeto.
-
La documentación de bucket inventory detalla la configuración y las opciones de instalación.
Método 3: ejecutar consultas complejas con MetaSearch
Diseñado para escenarios de consultas casi en tiempo real que filtran por prefijo, fecha o tipo de objeto.
En el panel de navegación izquierdo del bucket de destino, elija .
-
En la página Data Indexing, haga clic en Enable Now, seleccione MetaSearch y luego haga clic en Enable.
NotaHabilitar MetaSearch puede tomar cierto tiempo, según la cantidad de objetos del bucket.
Establezca Object Name como coincidencia de prefijo, introduzca
random_files/como prefijo y mantenga los demás parámetros con su configuración predeterminada.-
Configure el formato de salida.
Establezca Object Sort Order como Default.
En Data Aggregation, agregue Object Size mediante Sum.
-
Haga clic en Query Now. Los resultados muestran la cantidad total de objetos y el tamaño total del directorio
random_files/.Los resultados de la consulta indican que, en Data Aggregation, la suma de los tamaños de los archivos es de 14.47 GB. En Objects, cada archivo tiene un tamaño de 50 MB, el tipo de carga es Normal, la clase de almacenamiento es Standard y la lista de control de acceso (ACL) es Inherited from bucket.
La documentación de MetaSearch describe las opciones de configuración y consulta.
Consideraciones para producción
Control de acceso
En OSS, el control de acceso se basa en la coincidencia de prefijos de objetos, no en el objeto de directorio en sí.
Por ejemplo, para otorgar a un usuario acceso de solo lectura a todos los objetos del directorio logs/:
Incorrecto: establecer permisos sobre el objeto marcador de posición
logs/de cero bytes.Correcto: cree una política de RAM donde el campo
Resourcetenga el valoracs:oss:*:*:your-bucket-name/logs/*. Esta política coincide con todos los objetos que comienzan con el prefijologs/, sin importar si existe o no el objeto marcador de posiciónlogs/.
Optimización del rendimiento
Profundidad de directorios: evite estructuras muy anidadas, como
a/b/c/d/.../file.log, porque la lógica de filtrado de las operaciones de listado puede degradar el rendimiento.Cambios de nombre a gran escala: renombrar un directorio con muchos objetos genera un volumen alto de llamadas a la API y aumenta significativamente los costos de tráfico. Evite esta práctica en el diseño de su sistema.