All Products
Search
Document Center

JavaScript upload SDK

Last Updated: Jul 11, 2019

[TOC]

Installation

Import the following three JavaScript scripts to your webpage. For more information about the download address, see SDK download.

<! -- The es6-promise file is required for Internet Explorer. -->
    <script src="../lib/es6-promise.min.js"></script>
    <script src="../lib/aliyun-oss-sdk5.3.1.min.js"> </script>
    <script src="../aliyun-vod-upload-sdk1.5.0.min.js"></script>

Procedure

  1. Request for the upload URL and credential or the STS credential. For more information, see relevant documentation.
  2. Initialize the upload instance by using either the upload URL and credential or the STS credential.
  3. Set callbacks for reporting the upload progress and all upload statuses, including upload success, upload failure, and credential expiration.
  4. Add files to the upload list. Currently, video and image files can be uploaded.
  5. Start the upload.
  6. Handle callbacks.

Request for the upload URL and credential or the STS credential

Request for the upload URL and credential

You need to call different API operations to obtain the upload URL and credential for image and video files. Video upload from the client: The client sends an upload request to the AppServer. The AppServer calls the CreateUploadVideo operation to send a request to ApsaraVideo for VOD to obtain the upload URL and credential. If the request succeeds, the AppServer receives the upload URL, upload credential, and VideoId, and returns them to the client. Image upload from the client: The client sends an upload request to the AppServer. The AppServer calls the CreateUploadImage operation to send a request to ApsaraVideo for VOD to obtain the upload URL and credential. If the request succeeds, the AppServer receives the upload URL, upload credential, and ImageURL, and returns them to the client.

Request for the STS credential

The client sends an upload request to the AppServer. The AppServer sends a request to STS to obtain a temporary credential. If the request succeeds, the AppServer receives the STS credential and returns it to the client.

Initialize the upload instance

First, declare an initialization callback AliyunUpload.Vod.

var uploader = new AliyunUpload.Vod({
       // The ID of your Alibaba Cloud account. For more information about how to obtain the ID, see https://help.aliyun.com/knowledge_detail/37196.html.
       userId:"122"
       // The ID of the storage region of the file uploaded to ApsaraVideo for VOD. The default value is cn-shanghai. //eu-central-1,ap-southeast-1
       region:"",
       // The size of each part in multipart upload. The default value is 1 MB. The value cannot be less than 100 KB.
       partSize: 1048576,
       // The maximum number of parts that can be uploaded in parallel. The default value is 5.
       parallel: 5,
       // The maximum number of attempts to retry the upload upon a network exception. The default value is 3.
       retryCount: 3,
       // The interval for retrying the upload upon a network exception, in seconds. The default value is 2.
       retryDuration: 2,
      // This callback is fired when the upload starts.
      'onUploadstarted': function (uploadInfo) {
      }
      // This callback is fired when the upload succeeds.
      'onUploadSucceed': function (uploadInfo) {
      },
      // This callback is fired when the upload fails.
      'onUploadFailed': function (uploadInfo, code, message) {
      },
      // This callback is fired when the default or custom upload progress is reached. The progress is measured in bytes.
      'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
      },
      // This callback is fired when the upload credential expires.
      'onUploadTokenExpired': function (uploadInfo) {
      },
      // This callback is fired when all files are uploaded.
      'onUploadEnd':function(uploadInfo){
       }
  });

You do not need to set the upload URL and credential obtained in the first step during initialization. Instead, set them in the SDK by calling the setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress,videoId); method in the onUploadStarted callback that is fired when the upload starts. When the credential expires, the onUploadTokenExpired callback is fired. You need to call the resumeUploadWithAuth(uploadAuth) method to resume the upload with a new credential.

The sample code is as follows:

var uploader = new AliyunUpload.Vod({
       // The ID of your Alibaba Cloud account. You must specify the ID. For more information about how to obtain the ID, see https://help.aliyun.com/knowledge_detail/37196.html.
       userId:"122"
       // The ID of the storage region of the file uploaded to ApsaraVideo for VOD. The default value is cn-shanghai. //eu-central-1,ap-southeast-1
       region:"",
       // The size of each part in multipart upload. The default value is 1 MB. The value cannot be less than 100 KB.
       partSize: 1048576,
       // The maximum number of parts that can be uploaded in parallel. The default value is 5.
       parallel: 5,
       // The maximum number of attempts to retry the upload upon a network exception. The default value is 3.
       retryCount: 3,
       // The interval for retrying the upload upon a network exception, in seconds. The default value is 2.
       retryDuration: 2,
      // This callback is fired when the upload starts.
      'onUploadstarted': function (uploadInfo) {
        console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
        // Uses upload mode 1. In this mode, you need to call different operations to obtain the values of the uploadAuth and uploadAddress parameters, depending on whether the uploadInfo.videoId parameter has a value.
        if (uploadInfo.videoId) {
            // If the uploadInfo.videoId parameter has a value, call the RefreshUploadVideo operation. For more information, see https://help.aliyun.com/document_detail/55408.html.
         }
         else{
            // If the uploadInfo.videoId parameter does not have a value, call the CreateUploadVideo operation. For more information, see https://help.aliyun.com/document_detail/55407.html.
         }
        // Sets the values of the uploadAuth, uploadAddress, and videoId parameters obtained from ApsaraVideo for VOD in the SDK.
         uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
      }
      // This callback is fired when the upload succeeds.
      'onUploadSucceed': function (uploadInfo) {
        console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
      },
      // This callback is fired when the upload fails.
      'onUploadFailed': function (uploadInfo, code, message) {
        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
      },
      // This callback is fired when the default or custom upload progress is reached. The progress is measured in bytes.
      'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
          console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
      },
      // This callback is fired when the upload credential expires.
      'onUploadTokenExpired': function (uploadInfo) {
          console.log("onUploadTokenExpired");
          // During implementation, you need to call the RefreshUploadVideo operation to obtain a new value of the uploadAuth parameter based on the uploadInfo.videoId parameter.
          //https://help.aliyun.com/document_detail/55408.html
          // Sets the new value of the uploadAuth parameter obtained from ApsaraVideo for VOD in the SDK.        

          uploader.resumeUploadWithAuth(uploadAuth); 
      },
      // This callback is fired when all files are uploaded.
      'onUploadEnd':function(uploadInfo){
           console.log("onUploadEnd: uploaded all the files");
       }
  });

Use STS (upload mode 2)

You do not need to set the STS credential obtained in the first step during initialization. Instead, set it in the SDK by calling the setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken); method in the onUploadStarted callback that is fired when the upload starts. When the credential expires, the onUploadTokenExpired callback is fired. You need to call the resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken) method to resume the upload with a new credential.

var uploader = new AliyunUpload.Vod({
       // The ID of your Alibaba Cloud account. You must specify the ID. For more information about how to obtain the ID, see https://help.aliyun.com/knowledge_detail/37196.html.
       userId:"122"
       // The ID of the storage region of the file uploaded to ApsaraVideo for VOD. The default value is cn-shanghai. //eu-central-1,ap-southeast-1
       region:"",
       // The size of each part in multipart upload. The default value is 1 MB. The value cannot be less than 100 KB.
       partSize: 1048576,
       // The maximum number of parts that can be uploaded in parallel. The default value is 5.
       parallel: 5,
       // The maximum number of attempts to retry the upload upon a network exception. The default value is 3.
       retryCount: 3,
       // The interval for retrying the upload upon a network exception, in seconds. The default value is 2.
       retryDuration: 2,
      // This callback is fired when the upload starts.
      'onUploadstarted': function (uploadInfo) {
        console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
        // Obtains the STS credential and sets it in the SDK.
         uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken);
      }
      // This callback is fired when the upload succeeds.
      'onUploadSucceed': function (uploadInfo) {
        console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
      },
      // This callback is fired when the upload fails.
      'onUploadFailed': function (uploadInfo, code, message) {
        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
      },
      // This callback is fired when the default or custom upload progress is reached. The progress is measured in bytes.
      'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
          console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
      },
      // This callback is fired when the upload credential expires.
      'onUploadTokenExpired': function (uploadInfo) {
          console.log("onUploadTokenExpired");
          // Obtains a new STS credential and uses it to resume the upload.
          uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken);
      },
      // This callback is fired when all files are uploaded.
      'onUploadEnd':function(uploadInfo){
           console.log("onUploadEnd: uploaded all the files");
       }
  });

File list management

Add a file to be uploaded

Note: The size of the file to be uploaded cannot exceed 5 GB.

Use the standard HTML input type to select a file.

``` javascript

<form action="">
<input type="file" name="file" id="files" multiple/>
</form>
userData = '';
document.getElementById("files")
.addEventListener('change', function (event) {
for(var i=0; i<event.target.files.length; i++) {
// The logic code. 
}
});

```

Obtain the selected file and add it to the upload list.

``` javascript

uploader.addFile(event.target.files[i], null, null, null, userData);

```

When using STS to upload media files, you can specify whether to enable the watermark function and the priority of the job in the transcoding pipeline. The userData parameter is a JSON object. In this JSON object, you must enter the first Vod parameter, as shown in the following sample code. You can specify attributes such as Title in the Vod parameter. For more information about attributes supported by userData, see the CreateUploadVideo operation of ApsaraVideo for VOD.

``` javascript

var userData = '{"Vod":{"Title":"test","CateId":"234"}"}';

```

You need to specify userData in the SDK only if you use STS to upload media files. If you use the upload URL and credential to upload media files, you can specify userData in the call request of the CreateUploadVideo operation rather than specifying userData in the SDK.

Delete a file to be uploaded

The index parameter indicates the index of an element in the list returned by the listFiles method.

```
uploader.deleteFile(index);
```

Cancel upload of a single file

```
uploader.cancelFile(index);
```

Resume upload of a single file

```
uploader.resumeFile(index);
```

Obtain the upload list

```
uploader.listFiles();
var list = uploader.listFiles();
for (var i=0; i<list.length; i++) {
log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
}
```

Clear the upload list

```
uploader.cleanList();
```

Upload control

Start the upload

```
uploader.startUpload();
```

Stop the upload

```
uploader.stopUpload();
```

Resume the upload with a new upload credential upon credential expiration

```
uploader.resumeUploadWithAuth(uploadAuth);
```

Set the upload URL and credential

Call the setUploadAuthAndAddress method to set the upload URL and credential in the onUploadstarted callback. The callback parameters include the uploadInfo parameter. 

```
uploader.setUploadAuthAndAddress(uploadInfo,uploadAuth, uploadAddress, videoId);
```
> Note: For more information about how to obtain the upload URL and credential, see relevant documentation(~~52227~~).

Set the STS credential

Call the setSTSToken method to set the STS credential in the onUploadstarted callback. The callback parameters include the uploadInfo parameter. 

```
uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
```

Resume the upload with a new STS credential upon credential expiration

```
uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
```

Resumable upload

If the upload of a file fails halfway due to a certain reason and you upload the same file again later, the SDK resumes the upload from the last breakpoint. The SDK obtains the upload credential from the onUploadstarted callback. If you use upload mode 1, you need to call different ApsaraVideo for VOD API operations depending on the value of the videoId parameter returned by the callback. The sample code is as follows:

[CreateUploadVideo operation](~~55407~~)

[RefreshUploadVideo operation](~~55408~~)

[STS SDK reference](~~28788~~)

```
'onUploadstarted': function (uploadInfo) {
if (upload mode 1) {
if(! uploadInfo.videoId)// No exception occurs during upload of the file.
{
// Call the CreateUploadVideo operation in your actual environment.
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
}
else// If the videoId parameter has a value, update the upload credential based on the value.
{
// Call the RefreshUploadVideo operation in your actual environment.
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
}
}
else(upload mode 2)
{
// Call the operation for obtaining the STS credential in your actual environment.
uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
}

```

Obtain the breakpoint information

The parameter required by the getCheckpoint method is a file object.

```
uploader.getCheckpoint(file);
```