Você pode excluir um único arquivo (objeto), vários arquivos específicos, arquivos com um prefixo definido ou uma pasta e todo o seu conteúdo.
Objetos excluídos não podem ser recuperados. Proceda com cautela.
Precauções
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Inicialização (C SDK).
Para excluir um objeto, você deve ter a permissão
oss:DeleteObject. Para mais informações, consulte Conceder uma política personalizada.
Excluir um único arquivo
O código a seguir exclui o arquivo exampleobject.txt do bucket chamado examplebucket.
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the Endpoint for 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. */
const char *endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the file to delete. The full path cannot include the bucket name. */
const char *object_name = "exampleobject.jpg";
/* Set yourRegion to the Region ID of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize an aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
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"));
// Configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether a canonical name (CNAME) is used. A value of 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 the program entry 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) for memory management is equivalent to apr_pool_t. Its implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a memory pool. The second parameter is NULL, which indicates that the new 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 endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory to options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t object;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
/* Assign the char* type data to the aos_string_t type bucket. */
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
/* Delete the file. */
resp_status = oss_delete_object(oss_client_options, &bucket, &object, &resp_headers);
/* Check whether the file is deleted. */
if (aos_status_is_ok(resp_status)) {
printf("delete object succeed\n");
} else {
printf("delete object failed\n");
}
/* Release 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;
}
Excluir vários arquivos
Ao excluir arquivos manualmente, você pode excluir até 1.000 arquivos por vez. É possível excluir vários arquivos específicos, arquivos com um prefixo definido ou uma pasta e todo o seu conteúdo.
O OSS também suporta exclusão automática de arquivos mediante a configuração de regras de ciclo de vida. Para mais informações, consulte Regras de ciclo de vida baseadas na última modificação.
Excluir vários arquivos com nomes especificados
O código a seguir exclui vários arquivos com nomes especificados.
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the Endpoint for 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. */
const char *endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full paths of the files to delete. The full paths cannot include the bucket name. */
const char *object_name1 = "exampleobject1.jpg";
const char *object_name2 = "testobject2.png";
/* Set yourRegion to the Region ID of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize an aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
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"));
// Configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether a CNAME is used. A value of 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 the program entry 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) for memory management is equivalent to apr_pool_t. Its implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a memory pool. The second parameter is NULL, which indicates that the new 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 endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory to options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t object1;
aos_string_t object2;
int is_quiet = 1;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object1, object_name1);
aos_str_set(&object2, object_name2);
/* Build a list of files to delete. */
aos_list_t object_list;
aos_list_t deleted_object_list;
oss_object_key_t *content1;
oss_object_key_t *content2;
aos_list_init(&object_list);
aos_list_init(&deleted_object_list);
content1 = oss_create_oss_object_key(pool);
aos_str_set(&content1->key, object_name1);
aos_list_add_tail(&content1->node, &object_list);
content2 = oss_create_oss_object_key(pool);
aos_str_set(&content2->key, object_name2);
aos_list_add_tail(&content2->node, &object_list);
/* Delete the files in the list. `is_quiet` specifies whether to return the deletion results. */
resp_status = oss_delete_objects(oss_client_options, &bucket, &object_list, is_quiet, &resp_headers, &deleted_object_list);
if (aos_status_is_ok(resp_status)) {
printf("delete objects succeeded\n");
} else {
printf("delete objects failed\n");
}
/* Release 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;
}
Excluir vários arquivos com um prefixo especificado ou em uma pasta especificada
Se o valor do prefixo object_prefix no código de exemplo a seguir for uma string vazia ou NULL, todos os arquivos do bucket serão excluídos. Use esta operação com cautela.
O código a seguir exclui vários arquivos com um prefixo especificado ou uma pasta específica e todo o seu conteúdo.
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the Endpoint for 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. */
const char *endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* To delete all files that have the prefix src, set the prefix to src. This deletes all non-folder files with the prefix src, the src folder, and all files in the src folder. */
const char *object_prefix = "src";
/* Set yourRegion to the Region ID of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou. */
const char *region = "yourRegion";
/* To delete only the src folder and all files in it, set the prefix to src/. */
/* const char *object_prefix = "src/";*/
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize an aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
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"));
// Configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether a CNAME is used. A value of 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 the program entry 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) for memory management is equivalent to apr_pool_t. Its implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a memory pool. The second parameter is NULL, which indicates that the new 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 endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory to options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t prefix;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&prefix, object_prefix);
/* Delete files with the specified prefix. */
resp_status = oss_delete_objects_by_prefix(oss_client_options, &bucket, &prefix);
if (aos_status_is_ok(resp_status)) {
printf("delete objects by prefix succeeded\n");
} else {
printf("delete objects by prefix failed\n");
}
/* Release 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;
}
Referências
Para obter o código de exemplo completo para exclusão de um ou vários arquivos, consulte o exemplo no GitHub.
Operação de API para excluir um único arquivo: DeleteObject.
Operação de API para excluir vários arquivos: DeleteMultipleObjects.