Este tópico descreve como listar todos os arquivos (objetos) em um bucket especificado e como listar arquivos e subdiretórios em um diretório específico.
Observações de uso
Ao usar ferramentas de empacotamento como Webpack e Browserify, instale o OSS SDK for Browser.js executando o comando npm install ali-oss.
Se você tentar acessar um bucket do OSS pelo navegador sem regras CORS configuradas, o navegador rejeitará a requisição. Portanto, configure regras CORS no bucket para permitir o acesso via navegador. Para mais informações, consulte Instalação.
-
O OSS SDK for Browser.js é usado principalmente em navegadores. Para evitar a exposição do seu par de AccessKey, use credenciais de acesso temporárias obtidas pelo Security Token Service (STS) para acessar o OSS.
As credenciais de acesso temporárias consistem em um par de AccessKey e um token de segurança. O par de AccessKey inclui um AccessKey ID e um AccessKey secret. Para obter mais informações sobre como obter credenciais de acesso temporárias, consulte Usar STS para autorização de acesso temporário.
Listar todos os arquivos em um bucket
Use a função list para listar todos os arquivos no bucket atual:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
</head>
<body>
<script>
const client = new OSS({
// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: "yourRegion",
authorizationV4: true,
// The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token (SecurityToken) obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
async function list(dir) {
try {
// By default, a maximum of 1,000 files are returned.
let result = await client.list();
console.log(result);
// Continue to obtain the file list starting from the file that follows the last file read in the previous list operation.
if (result.isTruncated) {
result = await client.list({ marker: result.nextMarker });
}
// List files that have the prefix 'ex'.
result = await client.list({
prefix: "ex",
});
console.log(result);
// List files that have the prefix 'ex' and whose names come after 'example' in alphabetical order.
result = await client.list({
prefix: "ex",
marker: "example",
});
console.log(result);
} catch (e) {
console.log(e);
}
}
list();
</script>
</body>
</html>
Listar arquivos e subdiretórios em um diretório especificado
O OSS não tem o conceito de diretórios. Todos os elementos são armazenados como objetos. Para criar um diretório, crie um objeto de 0 KB com nome terminado em barra (/). Esse objeto pode ser enviado e baixado. O console do OSS exibe objetos terminados em barra (/) como diretórios. Use os parâmetros Delimiter e Prefix para simular a funcionalidade de diretórios:
Defina Prefix como o nome de um diretório para listar todos os arquivos que começam com esse prefixo. Essa ação lista recursivamente todos os arquivos e subdiretórios dentro desse diretório.
Defina também Delimiter como uma barra (/) para que a resposta liste apenas os arquivos e subdiretórios nesse diretório. Os nomes dos subdiretórios são retornados na seção SubDir. Arquivos e diretórios dentro desses subdiretórios não são listados.
Considere um bucket contendo os seguintes arquivos:
foo/x
foo/y
foo/bar/a
foo/bar/b
foo/hello/C/1
foo/hello/C/2
...
foo/hello/C/9999
Use a função listDir para listar os arquivos e subdiretórios em um diretório especificado:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
</head>
<body>
<script>
const client = new OSS({
// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from STS.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token (SecurityToken) obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
async function listDir(dir) {
try {
let result = await client.list({
prefix: dir,
// Set the delimiter for directories to a forward slash (/).
delimiter: "/",
});
result.prefixes.forEach(function (subDir) {
console.log("SubDir: %s", subDir);
});
result.objects.forEach(function (obj) {
console.log("Object: %s", obj.name);
});
} catch (e) {
console.log(e);
}
}
listDir();
</script>
</body>
</html>
A lista de arquivos retornada é a seguinte:
> listDir('foo/')
=> SubDir: foo/bar/
SubDir: foo/hello/
Object: foo/x
Object: foo/y
> listDir('foo/bar/')
=> Object: foo/bar/a
Object: foo/bar/b
> listDir('foo/hello/C/')
=> Object: foo/hello/C/1
Object: foo/hello/C/2
...
Object: foo/hello/C/9999
Referências
Para obter mais informações sobre a operação da API, consulte GetBucket (ListObjects).