All Products
Search
Document Center

Object Storage Service:Resumable upload

Last Updated:Sep 19, 2023

Before you upload an object to Object Storage Service (OSS) by using resumable upload, you can specify a directory for the checkpoint file that stores resumable upload records. If an object fails to be uploaded due to a network exception or program error, the upload task is resumed from the position recorded in the checkpoint file to upload the remaining data.

Usage notes

  • When you use packaging tools such as Webpack and Browserify, install OSS SDK for Browser.js by running the npm install ali-oss command.

  • If you want to access an OSS bucket from a browser but no CORS rules are configured for the bucket, the browser rejects the request. Therefore, you must configure CORS rules for a bucket if you want to access the bucket from a browser. For more information, see Installation.

  • In most cases, OSS SDK for Browser.js is used in browsers. To prevent your AccessKey pair from being exposed, we recommend that you use temporary access credentials obtained from Security Token Service (STS) to access OSS.

    The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information about how to obtain temporary access credentials, see Use STS for temporary access authorization.

Sample code

The following sample code provides an example on how to upload an object by using resumable upload:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <button id="submit">Upload</button>
    <button id="pause">Pause Upload</button>
    <button id="resume">Resume Upload</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 in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
       region: 'yourRegion',
       // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
       accessKeyId: 'yourAccessKeyId',
       accessKeySecret: 'yourAccessKeySecret',
       // Specify the security token obtained from STS. 
       stsToken: 'yourSecurityToken',
       // Specify the name of the bucket. Example: examplebucket. 
       bucket: "examplebucket",
    });
      // Create the object to upload by using resumable upload. The size of the object is 100 MB. 
      const fileContent = Array(1024 * 1024 * 100)
        .fill("a")
        .join("");
      const file = new File([fileContent], "multipart-upload-file");
      // Specify the full path of the object that is uploaded to the bucket. Example: exampledir/exampleobject.txt. 
      const name = "test.txt";
      // Define the checkpoint at which the object upload pauses. 
      let abortCheckpoint;
      // Obtain the DOM elements of the upload and the checkpoint. 
      const submit = document.getElementById("submit");
      const pause = document.getElementById("pause");
      // Obtain the DOM elements of the resumable upload task. 
      const resume = document.getElementById("resume");

      // Create a button that is used to upload the object. 
      submit.addEventListener("click", () => {
        client
          .multipartUpload(name, file, {
            progress: (p, cpt, res) => {
              // Assign a value to the checkpoint. 
              abortCheckpoint = cpt;
              console.log(abortCheckpoint);
              // Query the progress of the multipart upload task. 
              console.log(p * 100);
            },
          })
          .then((r) => console.log(r));
      });
      // Create a button that is used to pause the upload of the object. 
      pause.addEventListener("click", () => {
        // Pause the upload. 
        client.cancel();
      });

      const resumeUpload = async () => {
        // Set the number of upload retry operations to 5. 
        try {
          const result = await client.multipartUpload(name, file, {
            checkpoint: abortCheckpoint,
            progress: (p, cpt, res) => {
              // To implement resumable upload, you can save the checkpoint information during the upload. This way, after an upload exception occurs, the checkpoint is passed to multipartUpload as a parameter. Then, the upload is resumed from the byte at which last upload is paused. 
              abortCheckpoint = cpt;
              // Query the progress of the multipart upload task. 
              console.log(p);
            },
          });
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      };

      // Create a button that is used to resume the upload. 
      resume.addEventListener("click", async () => {
        await resumeUpload();
      });
    </script>
  </body>
</html>
            

References

For the complete sample code that is used to perform resumable upload, visit GitHub.