All Products
Search
Document Center

Object Storage Service:Resumable upload

Last Updated:Oct 13, 2023

An object can be split into several parts that can be uploaded at the same time. After all parts are uploaded, the parts are combined into a complete object.

Note

The sample code in this topic uses the catch method. To obtain the syntax of this method, view the Promise function defined in ECMAScript 6 and the async and await methods of this function. For more information about how to use the SDK, see Installation.

For more information about resumable upload, see Resumable upload. Lifecycle rules can be configured to periodically delete the parts that you no longer need. For more information, see Delete parts.

The progress parameter is provided to obtain the upload progress in callbacks. The SDK uses the upload progress and the checkpoint information as parameters in the callback requests. In resumable upload, checkpoint information is recorded. When the upload task fails because of errors, you can pass the checkpoint information to multipartUpload as a parameter to continue the upload.

Sample code

The following code provides an example on how to perform resumable upload:

const OSS = require('ali-oss')

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
});

// Specify the local path of the uploaded file. 
const filePath = "yourfilepath";

let checkpoint;
async function resumeUpload() {
  // Set the number of upload retry operations to 5. 
  for (let i = 0; i < 5; i++) {
    try {
      const result = await client.multipartUpload('object-name', filePath, {
        checkpoint,
        async progress(percentage, cpt) {
          checkpoint = cpt;
        },
      });
      console.log(result);
      break; // Break out of the loop. 
    } catch (e) {
      console.log(e);
    }
  }
}

resumeUpload();

In the preceding code, the checkpoint information is recorded as a variable. If the program crashes, the checkpoint information is lost. We recommend that you save the checkpoint information in a file. This way, the program can obtain the checkpoint information from the file after the program restarts.

References

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