Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar pastas (Browser.js SDK)

Última atualização: Jul 03, 2026

O OSS oferece diretórios que simulam uma estrutura de pastas, facilitando a organização, a localização e a execução de operações em massa em grandes quantidades de objetos.

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 de CORS configuradas, o navegador rejeitará a solicitação. Portanto, configure regras de 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 adquirir credenciais de acesso temporárias, consulte Usar STS para autorização de acesso temporário.

Criar um diretório

<!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 = OSS({
        // Set yourRegion to the region where the bucket is located. For example, if the region is China (Hangzhou), set yourRegion to oss-cn-hangzhou.
        region: 'yourRegion',
        authorizationV4: true,
        // The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from the STS service.
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // The security token (SecurityToken) obtained from the STS service.
        stsToken: 'yourSecurityToken',
        // Specify the bucket name.
        bucket: 'examplebucket'
      });
      // Specify the directory name. The directory name must end with a forward slash (/).
      client
        .put("log/", new Blob([]))
        .then((r) => {
          console.log(r);
        })
        .catch((e) => {
          console.log(e);
        });
    </script>
  </body>
</html>

Excluir um diretório

Exclua um diretório e todos os seus objetos especificando um Prefix. Por exemplo, para excluir o diretório log do bucket examplebucket, defina Prefix como log/.

Aviso

A exclusão de um diretório remove também todos os seus subdiretórios e objetos. Proceda com cautela.

<!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 region is China (Hangzhou), set yourRegion to oss-cn-hangzhou.
        region: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey ID and AccessKey secret obtained from the STS service.
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // The security token obtained from the STS service.
        stsToken: 'yourSecurityToken',
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
      });

      // Handle request failures. This prevents promise.all from being interrupted and returns the failure reason and the name of the failed file.
      async function handleDel(name, options) {
        try {
          await client.delete(name);
        } catch (error) {
          error.failObjectName = name;
          return error;
        }
      }

      // Delete multiple files.
      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 a directory and all files in the directory.
      deletePrefix("log/");
    </script>
  </body>
</html>

Referências

  • Para obter mais informações sobre as operações de API usadas para criar um diretório, consulte PutObject e CreateDirectory.

  • Para obter detalhes sobre a operação de API usada para excluir pastas e todo o seu conteúdo, consulte DeleteObject.