Todos los productos
Search
Centro de documentos

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

Última actualización: Sep 03, 2026

Object Storage Service (OSS) ofrece una función de carga multiparte que divide un archivo grande, u objeto, en varias partes. Estas partes se pueden cargar de forma independiente. Una vez cargadas todas las partes, puede llamar a la operación CompleteMultipartUpload para combinarlas en un solo objeto. Este proceso permite reanudar las cargas interrumpidas.

Precauciones

  • Antes de realizar una carga multiparte, asegúrese de comprender esta función. Para obtener más información, consulte Multipart upload.

  • Si utiliza una herramienta de empaquetado como webpack o browserify, instale el kit de desarrollo de software (SDK) Browser.js mediante el comando npm install ali-oss.

  • El acceso a OSS desde un navegador implica solicitudes de origen cruzado. Si no configura las reglas de origen cruzado, el navegador rechazará estas solicitudes. Para acceder a OSS desde un navegador, debe configurar las reglas de origen cruzado en OSS. Para obtener más información, consulte Preparations.

  • El Browser.js SDK se utiliza generalmente en entornos de navegador. Para evitar exponer el par de AccessKey (AccessKey ID y AccessKey secret) de su cuenta de Alibaba Cloud, utilice credenciales de acceso temporal para realizar operaciones en OSS.

    Las credenciales de acceso temporal incluyen un par de AccessKey temporal (AccessKey ID y AccessKey secret) y un token de seguridad. Para obtener más información sobre cómo conseguir credenciales de acceso temporal, consulte Grant access (Browser.js SDK).

Código de ejemplo completo para la carga multiparte

Para cargar un archivo grande, puede utilizar la operación MultipartUpload. Esta operación divide el archivo en varios bloques de datos, o partes, que se pueden cargar por separado. Si algunas partes fallan durante la carga, OSS guarda el progreso. Solo es necesario volver a cargar las partes que fallaron, no todo el archivo.

Importante

Para archivos mayores a 100 MB, utilice la carga multiparte. Las cargas reanudables y los reintentos ayudan a aumentar la tasa de éxito. Si utiliza la carga multiparte para un archivo menor a 100 MB con un partSize inadecuado, es posible que el progreso de la carga no se muestre completamente. Para archivos menores a 100 MB, utilice la carga simple.

A continuación se muestra cómo usar la carga multiparte para cargar un archivo llamado exampleobject.txt en el 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>

Si ocurre un error ConnectionTimeoutError al llamar a la operación MultipartUpload, debe gestionar el tiempo de espera. Por ejemplo, puede reducir el tamaño de la parte, aumentar el periodo de tiempo de espera, reintentar la solicitud o capturar el error ConnectionTimeoutError. Para obtener más información, consulte Handle network errors.

Cancelar un evento de carga multiparte

Puede llamar al método client.abortMultipartUpload para cancelar un evento de carga multiparte. Después de cancelar un evento, no podrá usar su uploadId para ninguna operación y los datos de las partes cargadas se eliminarán.

A continuación se muestra cómo cancelar un evento de carga multiparte:

<!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 las partes cargadas

Puede llamar al método client.listParts para listar todas las partes cargadas correctamente correspondientes a un uploadId específico.

A continuación se muestra cómo listar las partes cargadas:

<!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 carga multiparte

Puede llamar al método client.listUploads para listar todos los eventos de carga multiparte en curso. Los eventos en curso son aquellos que se han iniciado pero que aún no se han completado ni cancelado.

A continuación se muestra cómo listar eventos de carga multiparte:

<!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>

Referencias

  • Para ver el código de ejemplo completo de la carga multiparte, consulte Ejemplo en GitHub.

  • El método multipartUpload, utilizado para la carga multiparte en el Browser.js SDK, encapsula las siguientes tres operaciones de API:

    • Para obtener más información sobre la operación de API que inicializa un evento de carga multiparte, consulte InitiateMultipartUpload.

    • Para obtener más información sobre la operación de API que carga una parte, consulte UploadPart.

    • Para obtener más información sobre la operación de API que completa una carga multiparte, consulte CompleteMultipartUpload.

  • Para obtener más información sobre la operación de API que cancela un evento de carga multiparte, consulte AbortMultipartUpload.

  • Para obtener más información sobre la operación de API que lista las partes cargadas, consulte ListParts.

  • Para obtener más información sobre la operación de API que lista todos los eventos de carga multiparte en curso, consulte ListMultipartUploads.

Preguntas frecuentes

¿Cómo resuelvo el error "PLease set the etag of expose-headers in Oss."?

  • Causa

    La compartición de recursos de origen cruzado (CORS) no está configurada correctamente.

  • Solución

    Configure CORS para el bucket actual. Al configurar las reglas de CORS, debe exponer encabezados comunes como x-oss-request-id y ETag. Para obtener más información, consulte Configure CORS.

¿Cómo resuelvo el error "The operation is not supported for this resource."?

  • Causa

    Estableció la clase de almacenamiento del objeto al llamar a la operación CompleteMultipartUpload.

  • Solución

    No es posible establecer la clase de almacenamiento del objeto al llamar a CompleteMultipartUpload. Para especificar la clase de almacenamiento del objeto en una carga multiparte, debe definirla al llamar a InitiateMultipartUpload.