Todos os produtos
Search
Central de documentação

Object Storage Service:Multipart upload (Browser.js SDK)

Última atualização: Sep 22, 2026

O Object Storage Service (OSS) oferece o recurso de upload multipart, que divide um arquivo grande, ou objeto, em várias partes. É possível enviar essas partes de forma independente. Após enviar todas as partes, chame a operação CompleteMultipartUpload para combiná-las em um único objeto. Esse processo permite a retomada de uploads.

Precauções

  • Antes de iniciar um upload multipart, certifique-se de compreender o recurso. Para mais informações, consulte Multipart upload.

  • Se usar uma ferramenta de empacotamento como webpack ou browserify, instale o kit de desenvolvimento de software (SDK) Browser.js executando o comando npm install ali-oss.

  • O acesso ao OSS a partir de um navegador envolve requisições de origem cruzada. Caso não configure as regras de origem cruzada, o navegador bloqueará essas requisições. Para acessar o OSS pelo navegador, configure as regras de origem cruzada no OSS. Para mais informações, consulte Preparations.

  • O SDK Browser.js é amplamente utilizado em ambientes de navegador. Para evitar expor o par de AccessKey (AccessKey ID e AccessKey secret) da sua conta Alibaba Cloud, use credenciais de acesso temporárias para executar operações do OSS.

    As credenciais de acesso temporárias incluem um par de AccessKey temporário (AccessKey ID e AccessKey secret) e um token de segurança. Para mais informações sobre como obter as credenciais de acesso temporárias, consulte Grant access (Browser.js SDK).

Código de exemplo completo para upload multipart

Para enviar um arquivo grande, use a operação MultipartUpload. Essa operação divide o arquivo em vários blocos de dados, ou partes, que você pode enviar separadamente. Se o envio de algumas partes falhar, o OSS salva o progresso. Será necessário reenviar apenas as partes com falha, e não o arquivo inteiro.

Importante

Para arquivos maiores que 100 MB, use o upload multipart. A retomada de uploads e as novas tentativas ajudam a aumentar a taxa de sucesso. Ao usar o upload multipart para um arquivo menor que 100 MB com um partSize inadequado, o progresso do envio pode não ser exibido por completo. Para arquivos menores que 100 MB, use o upload simples.

O código a seguir demonstra o uso do upload multipart para enviar um arquivo chamado exampleobject.txt para o bucket examplebucket.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="submit">Upload</button>
    <input id="file" type="file" />
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
        region: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey ID and AccessKey secret obtained from STS.
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // The security token obtained from STS.
        stsToken: "yourSecurityToken",
        // Specify the bucket name, for example, examplebucket.
        bucket: "examplebucket",
      });

      const headers = {
        // Specify the caching behavior of the web page when the object is downloaded.
        "Cache-Control": "no-cache",
        // Specify the name of the object when it is downloaded.
        "Content-Disposition": "example.txt",
        // Specify the expiration time in milliseconds.
        Expires: "1000",
        // Specify the storage class of the object.
        "x-oss-storage-class": "Standard",
        // Specify tags for the object. You can specify multiple tags.
        "x-oss-tagging": "Tag1=1&Tag2=2",
        // Specify whether to overwrite an object that has the same name when you initialize a multipart upload. A value of true indicates that overwriting is prohibited.
        "x-oss-forbid-overwrite": "true",
      };

      // Specify the name of the object to be uploaded to examplebucket, for example, exampleobject.txt.
      const name = "exampleobject.txt";
      // Get the DOM.
      const submit = document.getElementById("submit");
      const options = {
        // Obtain the multipart upload progress, checkpoint, and return value.
        progress: (p, cpt, res) => {
          console.log(p);
        },
        // Set the number of parts to upload concurrently.
        parallel: 4,
        // Set the part size. The default value is 1 MB. The minimum value is 100 KB. The maximum value is 5 GB. The size of the last part can be smaller than 100 KB.
        partSize: 1024 * 1024,
        // headers,
        // Custom metadata. You can obtain the metadata of the object by calling the HeadObject operation.
        meta: { year: 2020, people: "test" },
        mime: "text/plain",
      };

      // Add a listener to the button.
      submit.addEventListener("click", async () => {
        try {
          const data = document.getElementById("file").files[0];
          // Perform multipart upload.
          const res = await client.multipartUpload(name, data, {
            ...options,
            // Set the upload callback.
            // If no callback server is involved, delete the callback settings.
            callback: {
              // Set the server address for the callback request.
              url: "http://examplebucket.aliyuncs.com:23450",
              // Set the Host value in the header of the callback request. This is the Host value configured on your server.
              host: "yourHost",
              /* eslint no-template-curly-in-string: [0] */
              // Set the value of the request body when a callback is initiated.
              body: "bucket=${bucket}&object=${object}&var1=${x:var1}",
              // Set the Content-Type of the callback request.
              contentType: "application/x-www-form-urlencoded",
              customValue: {
                // Set custom parameters for the callback request.
                var1: "value1",
                var2: "value2",
              },
            },
          });
          console.log(res);
        } catch (err) {
          console.log(err);
        }
      });
    </script>
  </body>
</html>

Se ocorrer um ConnectionTimeoutError ao chamar a operação MultipartUpload, trate o erro de tempo limite. Por exemplo, reduza o tamanho da parte, aumente o período de tempo limite, repita a requisição ou capture o ConnectionTimeoutError. Para mais informações, consulte Handle network errors.

Cancelar um evento de upload multipart

Chame o método client.abortMultipartUpload para cancelar um evento de upload multipart. Após cancelar um evento, não é possível usar o uploadId do evento para nenhuma operação, e o OSS exclui os dados das partes enviadas.

O código a seguir mostra como cancelar um evento de upload multipart:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="submit">Upload</button>
    <button id="abort">Abort</button>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
        region: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey ID and AccessKey secret obtained from STS.
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // The security token obtained from STS.
        stsToken: "yourSecurityToken",
        // Specify the bucket name, for example, examplebucket.
        bucket: "examplebucket",
      });
      // Generate a 100 MB file for multipart upload.
      const fileContent = Array(1024 * 1024 * 100)
        .fill("a")
        .join("");
      const file = new File([fileContent], "multipart-upload-file");
      // Set the name of the object to be uploaded to examplebucket, for example, exampleobject.txt.
      const name = "exampleobject.txt";
      // Set the checkpoint.
      let abortCheckpoint;
      // Get the DOM.
      const submit = document.getElementById("submit");
      const abort = document.getElementById("abort");

      // Add a listener to the upload button. After you click Upload, multipart upload starts.
      submit.addEventListener("click", async () => {
        try {
          const res = await client.multipartUpload(name, file, {
            progress: (p, cpt, res) => {
              // Assign a value to the checkpoint.
              abortCheckpoint = cpt;
              // Obtain the upload progress.
              console.log(p);
            },
          });
        } catch (err) {
          console.log(err);
        }
      });
      // Add a listener to the abort button.
      abort.addEventListener("click", () => {
        // Abort the multipart upload.
        client.abortMultipartUpload(
          abortCheckpoint.name,
          abortCheckpoint.uploadId
        );
      });
    </script>
  </body>
</html>

Listar partes enviadas

Chame o método client.listParts para listar todas as partes enviadas com êxito para um uploadId especificado.

O código a seguir mostra como listar as partes enviadas:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="submit">Upload</button>
    <button id="check">List uploaded parts</button>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
         // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
         region: 'yourRegion',
         authorizationV4: true,
         // The temporary AccessKey ID and AccessKey secret obtained from STS.
         accessKeyId: 'yourAccessKeyId',
         accessKeySecret: 'yourAccessKeySecret',
         // The security token obtained from STS.
        stsToken: 'yourSecurityToken',
        // Specify the bucket name, for example, examplebucket.
        bucket: "examplebucket",
      });
      // Generate a 100 MB file for multipart upload.
      const fileContent = Array(1024 * 1024 * 100)
        .fill("a")
        .join("");
      const file = new File([fileContent], "multipart-upload-file");
      // Set the name of the object to be uploaded to examplebucket, for example, exampleobject.txt.
      const name = "exampleobject.txt";
      // Set the checkpoint.
      let abortCheckpoint;

      // Get the DOM.
      const submit = document.getElementById("submit");
      const check = document.getElementById("check");

      // Add a listener to the button.
      submit.addEventListener("click", async () => {
        try {
          const res = await client.multipartUpload(name, file, {
            progress: (p, cpt, res) => {
              // Assign a value to the checkpoint.
              abortCheckpoint = cpt;
              // Obtain the upload progress.
              console.log("progress=====", p);
            },
          });
        } catch (err) {
          console.log(err);
        }
      });
      // Add a listener to the button.
      check.addEventListener("click", async () => {
        // List the uploaded parts.
        const result = await client.listParts(name, abortCheckpoint.uploadId);
        console.log(result);
      });
    </script>
  </body>
</html>

Listar eventos de upload multipart

Chame o método client.listUploads para listar todos os eventos de upload multipart em andamento. Eventos em andamento são aqueles iniciados, mas ainda não concluídos ou cancelados.

O código a seguir mostra como listar eventos de upload multipart:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="check">List multipart upload events</button>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
         // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
         region: 'yourRegion',
         authorizationV4: true,
         // The temporary AccessKey ID and AccessKey secret obtained from STS.
         accessKeyId: 'yourAccessKeyId',
         accessKeySecret: 'yourAccessKeySecret',
         // The security token obtained from STS.
        stsToken: 'yourSecurityToken',
        // Specify the bucket name, for example, examplebucket.
        bucket: "examplebucket",
      });
      // Get the DOM.
      const check = document.getElementById("check");

      // Add a listener to the button.
      check.addEventListener("click", async () => {
        // Obtain all multipart upload events that are initiated but not completed or canceled.
        const result = await client.listUploads({ "max-uploads": 100 });
        console.log("uploads", result.uploads);
      });
    </script>
  </body>
</html>

Referências

  • Para obter o código de exemplo completo de upload multipart, consulte Exemplo no GitHub.

  • O método multipartUpload, utilizado no upload multipart no SDK Browser.js, encapsula as três operações de API a seguir:

    • Para mais informações sobre a operação de API para inicializar um evento de upload multipart, consulte InitiateMultipartUpload.

    • Para mais detalhes sobre a operação de API para enviar uma parte, consulte UploadPart.

    • Para obter mais informações sobre a operação de API para concluir um upload multipart, consulte CompleteMultipartUpload.

  • Para saber mais sobre a operação de API para cancelar um evento de upload multipart, consulte AbortMultipartUpload.

  • Para mais informações sobre a operação de API para listar partes enviadas, consulte ListParts.

  • Para mais detalhes sobre a operação de API para listar todos os eventos de upload multipart em andamento, consulte ListMultipartUploads.

Perguntas frequentes

Como resolver o erro "PLease set the etag of expose-headers in Oss."?

  • Causa

    O compartilhamento de recursos de origem cruzada (CORS) não está configurado corretamente.

  • Solução

    Configure o CORS para o bucket atual. Ao configurar as regras de CORS, exponha cabeçalhos comuns, como x-oss-request-id e ETag. Para mais informações, consulte Configure CORS.

Como resolver o erro "The operation is not supported for this resource."?

  • Causa

    Você definiu a classe de armazenamento do objeto ao chamar a operação CompleteMultipartUpload.

  • Solução

    Não é possível definir a classe de armazenamento do objeto ao chamar CompleteMultipartUpload. Para especificar a classe de armazenamento do objeto em um upload multipart, defina-a ao chamar InitiateMultipartUpload.