Cette rubrique explique comment répertorier tous les objets d'un bucket à l'aide du kit SDK Object Storage Service (OSS) pour Harmony.
Remarques sur l'utilisation
Pour obtenir la liste des régions et des endpoints pris en charge par OSS, consultez la rubrique Régions et endpoints.
Pour répertorier les objets, vous devez disposer de l'autorisation
oss:ListObjects. Pour plus d'informations, consultez la rubrique Attacher une stratégie personnalisée à un utilisateur RAM.
Exemple de code
L'exemple de code suivant montre comment appeler l'opération ListObjectsV2 pour répertorier les objets d'un 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();