Help Center/ Object Storage Service/ SDK Reference/ BrowserJS/ FAQs/ How Do I Suspend a Resumable Upload Task?
Updated on 2024-04-26 GMT+08:00

How Do I Suspend a Resumable Upload Task?

The API for resumable upload supports the suspension of upload tasks. The code example is as follows:

// Create an instance of ObsClient.
var obsClient = new ObsClient({
    // Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, configure environment variables AccessKeyID and SecretAccessKey.
    // The front-end code does not have the process environment variable, so you need to use a module bundler like webpack to define the process variable.
    // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html.
    access_key_id: process.env.AccessKeyID,
    secret_access_key: process.env.SecretAccessKey,
    // Replace the example endpoint with the actual one in your case.
    server: 'https://obs.eu-west-101.myhuaweicloud.eu'
});

var uploadCheckpoint;
obsClient.uploadFile({
       Bucket : 'bucketname',
       Key : 'objectname',
       SourceFile : document.getElementById('input-file').files[0],
       PartSize : 9 * 1024 * 1024,
       ProgressCallback : function(transferredAmount, totalAmount, totalSeconds){
           // Obtain the upload progresses.
           console.log(transferredAmount * 1.0 / totalSeconds / 1024);
           console.log(transferredAmount * 100.0 / totalAmount);
       },
       ResumeCallback : function(resumeHook, uploadCheckpoint){
           // If the upload is suspended after running for three seconds, the API returns an error.
           setTimeout(function(){
              hook.cancel();
           }, 3000);
           // Record a breakpoint.
           cp = uploadCheckpoint;
       }
}, function(err, result){
    console.error('Error-->' + err);
    // If an error occurs, call the resumable upload API again to continue the upload task.
    if(err){
       obsClient.uploadFile({
          UploadCheckpoint : uploadCheckpoint,
          ProgressCallback : function(transferredAmount, totalAmount, totalSeconds){
           // Obtain the upload progresses.
              console.log(transferredAmount * 1.0 / totalSeconds / 1024);
              console.log(transferredAmount * 100.0 / totalAmount);
          },
        }, function(err, result){
           // Reprocess the callback function.
        });
    }else {
         console.log('Status-->' + result.CommonMsg.Status);
         console.log('RequestId-->' + result.CommonMsg.RequestId);
    }
});