Este tópico descreve como listar todos os objetos em um bucket com o SDK do Object Storage Service (OSS) para Harmony.
Observações de uso
Para informações sobre regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints.
A listagem de objetos exige a permissão
oss:ListObjects. Para mais detalhes, consulte Anexar uma política personalizada a um usuário RAM.
Código de exemplo
O exemplo a seguir demonstra como chamar a operação ListObjectsV2 para listar objetos em um bucket:
import Client, { RequestError } from '@aliyun/oss';
// Create an OSSClient instance.
const client = new Client({
// Specify the AccessKey ID obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
// Specify the AccessKey secret obtained from STS.
accessKeySecret: 'yourAccessKeySecret',
// Specify the security token obtained from STS.
securityToken: 'yourSecurityToken',
// 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: 'oss-cn-hangzhou',
});
/**
* List objects in a bucket.
* Use the listObjectsV2 method to list objects in the bucket and the metadata of the objects.
*/
const listObjectsV2 = async () => {
try {
// Use the listObjectsV2 method to list objects in the bucket and the metadata of the objects.
const res = await client.listObjectsV2({
bucket: 'yourBucketName', // Specify the name of the bucket.
});
// Display the objects and their metadata.
console.log(JSON.stringify(res));
} catch (err) {
// Capture the exceptions during the request.
if (err instanceof RequestError) {
// If known types of errors exist, display information, such as the error code, error message, request ID, HTTP status code, and EC.
console.log('code: ', err.code); // The error code.
console.log('message: ', err.message); // The error message.
console.log('requestId: ', err.requestId); // The request ID.
console.log('status: ', err.status); // The HTTP status code.
console.log('ec: ', err.ec); // The EC.
} else {
// Display other unknown types of errors.
console.log('unknown error: ', err);
}
}
};
// Call the listObjectsV2 function to list objects in the bucket.
listObjectsV2();