Upload SDK for JavaScript

Updated at:
Copy as MD

Use the JavaScript upload SDK to upload media files to ApsaraVideo VOD.

Browser requirements

Browser

Supported

Version

IE

✔️

Internet Explorer 10 and later

Microsoft Edge

✔️

All

Chrome

✔️

Mainstream browser versions

Firefox

✔️

Safari

✔️

Android default browser

✔️

iOS default browser

✔️

Windows Phone default browser

✔️

Feature description

The JavaScript upload SDK supports audio, video, and image uploads only. Auxiliary media assets are not supported.

SDK and demo download

Integration methods

The JavaScript upload SDK depends on the OSS SDK. Set window.OSS to a valid value. Otherwise, ReferenceError: OSS is not defined occurs.

(Recommended) Import by using <script> in HTML code

<!--  es6-promise is required for Internet Explorer. Internet Explorer 10 and later are supported. -->
  <script src="../lib/es6-promise.min.js"></script>
  <script src="../lib/aliyun-oss-sdk-6.17.1.min.js"></script>
  <script src="../aliyun-upload-sdk-1.5.7.min.js"></script>

Import by using a module

Manually assign the OSS module to window.OSS:

Note

Skip this step if you already included the files via <script> tags.

import OSS from '../lib/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min'
window.OSS = OSS;
import '../lib/aliyun-upload-sdk/aliyun-upload-sdk-1.5.7.min'

Basic settings

Initialize the upload instance

  • Specify the userId parameter to identify the uploader. Use an Alibaba Cloud account ID or a custom user ID from Alibaba Cloud Account Center. If userId is null or unspecified, an error occurs.

  • Set the region parameter to a supported ApsaraVideo VOD region ID. For more information, see ApsaraVideo VOD region IDs.

var uploader = new AliyunUpload.Vod({
  // Required. The identity of the uploader. The value can be an Alibaba Cloud account ID or a custom user ID. You can view the ID in Alibaba Cloud Account Center (https://account-console.alibabacloud.com/).
  userId: "122",
  // The regions where you want to upload the files. Default value: cn-shanghai. 
  // Examples: eu-central-1 and ap-southeast-1.
  region: "",
  // The size of each part in a multipart upload. Unit: bytes. The size cannot be smaller than 100 KB (100 × 1024). Default size: 1 MB (1 × 1024 × 1024).
  partSize: 1048576,
  // The maximum number of parts that can be uploaded in parallel. Default value: 5.
  parallel: 5,
  // The maximum number of times the system retries the upload when a network error occurs. Default value: 3.
  retryCount: 3,
  // The interval at which the system retries the upload when a network error occurs. Default value: 2. Unit: seconds.
  retryDuration: 2,
  // The upload is started.
  onUploadstarted: function (uploadInfo) {},
  // The upload is successful.
  onUploadSucceed: function (uploadInfo) {},
  // The upload fails.
  onUploadFailed: function (uploadInfo, code, message) {},
  // The upload progress. Unit: bytes.
  onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {},
  // The upload credential or STS token expires.
  onUploadTokenExpired: function (uploadInfo) {},
  // All files are uploaded.
  onUploadEnd: function (uploadInfo) {},
});

Configure the credential

Before you proceed, understand the client upload process and deploy an authorization service. For more information, see Upload from clients.

  1. If you use Method 1: Upload URL and credential, obtain upload URLs and credentials from the authorization service.

  2. If you use Method 2: STS token, obtain an STS token from the authorization service. For more information, see Obtain an STS token.

Configure the returned authorization information in the onUploadstarted callback. When the credential expires, the onUploadTokenExpired callback fires. Re-obtain a credential by calling the refresh operation.

Method 1: Upload URL and credential

Call setUploadAuthAndAddress to configure the upload URL and credential. If the credential expires, the onUploadTokenExpired callback fires. Call resumeUploadWithAuth with a new credential to resume the upload.

// The upload is started.
onUploadstarted: function (uploadInfo) {
  let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
  axios.get(refreshUrl).then(({data}) => {
    let uploadAuth = data.UploadAuth
    let uploadAddress = data.UploadAddress
    let videoId = data.VideoId
    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
  })
},
// The upload credential expires.
onUploadTokenExpired: function (uploadInfo) {
  // If the upload of a large file times out when you use Method 1 (UploadAuth),
  // call the RefreshUploadVideo operation based on uploadInfo.videoId and re-obtain the value of UploadAuth.
  // Then, call the resumeUploadWithAuth method. In this example, the value of UploadAuth is directly obtained because resumeUploadWithAuth is a test method.
  let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
  axios.get(refreshUrl).then(({data}) => {
    let uploadAuth = data.UploadAuth
    uploader.resumeUploadWithAuth(uploadAuth)
    console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
  })
  self.statusText = 'The upload times out...'
},

Method description

uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
uploader.resumeUploadWithAuth(uploadAuth)

Parameter

Description

uploadInfo

The first parameter of the onUploadstarted callback.

uploadAuth

The upload credential returned by the CreateUploadVideo operation.

uploadAddress

The upload URL returned by the CreateUploadVideo operation.

videoId

The audio or video ID returned by the CreateUploadVideo operation.

Method 2: STS token

Call setSTSToken to configure the STS token. If the token expires, the onUploadTokenExpired callback fires. Call resumeUploadWithSTSToken with a new token to resume the upload.

 /*Callback method - The upload is started.*/
 onUploadstarted: function (uploadInfo) {
    let stsUrl = "***.***.stsUrl" /*Use the setSTSToken method to obtain the STS token.*/
    axios.get(stsUrl).then(({data}) => {
          var info = data.SecurityTokenInfo
          uploader.setSTSToken(uploadInfo, info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
     })
 },
/*Callback method - The credential times out.*/
 onUploadTokenExpired: function (uploadInfo) { 
     let stsUrl = "***.***.stsUrl"  /*Use the resumeUploadWithSTSToken method to refresh the STS token.*/
     axios.get(stsUrl).then(({data}) => {
         var info = data.SecurityTokenInfo  
         uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);      
     })
 },

Method description

uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken)
uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken)

Parameter

Description

uploadInfo

The first parameter of the onUploadstarted callback.

accessKeyId

The AccessKeyId field in the STS token.

accessKeySecret

The AccessKeySecret field in the STS token.

secretToken

The SecretToken field in the STS token.

Add files

Listen for the change event on <input type="file" /> to add files to the uploader list.

Native JavaScript

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

Vue

 <template>
  <input type="file" id="fileUpload" @change="fileChange($event)">
 </template>

<script>
  export default {
    data () {
      return {
        file: null,
      }
    },
    methods: {
      fileChange (e) {
        this.file = e.target.files[0]
        if (!this.file) {
          alert("Select the files that you want to upload.")
          return
        }
        var Title = this.file.name
        var userData = '{"Vod":{}}'
        if (this.uploader) {
          this.uploader.stopUpload()
        }
        // Initialize an uploader.
        this.uploader = this.createUploader() 
        this.uploader.addFile(this.file, null, null, null, userData)
      },
    }
  }
</script>

Method description

uploader.addFile(file,endpoint,bucket,object,paramData)

Parameter

Required

Type

Description

file

Yes

File

The file to upload.

endpoint

No

String

The OSS endpoint. If null, AppServer selects the endpoint.

bucket

No

String

The target bucket. If null, AppServer selects the bucket.

object

No

String

The target object. If null, AppServer selects the object.

paramData

No

String

File metadata such as title, description, transcoding, and callback settings. Specify paramData when using STS token upload.

The value of the paramData parameter is a JSON string. Example: '{"Vod":{}}'. You must specify Vod in the request. You can nest parameters supported by the paramData parameter under Vod. You can nest the request parameters of the CreateUploadVideo or CreateUploadImage operation.

Start the upload

uploader.startUpload();
  1. After the file upload is started, the onUploadProgress callback is invoked to synchronize the upload progress.

  2. If the file upload is successful, the onUploadSucceed callback is invoked to return the upload result.

Show the upload progress

// The file upload progress. Unit: bytes. You can use this function to obtain the upload progress and display the upload progress on the page.
onUploadProgress: function (uploadInfo, totalSize, progress) {
  console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
  let progressPercent = Math.ceil(progress * 100)
  self.authProgress = progressPercent
  self.statusText = 'The upload is ongoing...'
},

Obtain the upload result

// The upload is successful.
onUploadSucceed: function (uploadInfo) {
  console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  self.statusText = 'The upload is successful!'
},
// The upload fails.
onUploadFailed: function (uploadInfo, code, message) {
  console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
  self.statusText = 'The upload fails!'
},
  • After a video is uploaded, use videoId to obtain the playback URL. For more information, see Obtain a playback credential.

  • imageUrl is not returned automatically for image uploads. Configure a callback to obtain it. For more information, see Configure callbacks.

Advanced features

Use upload acceleration

Enable upload acceleration for large files (GB/TB) or cross-region uploads, such as from the Chinese mainland to the Singapore region.

To enable upload acceleration, submit a ticket. Provide your Account ID and the bucket to accelerate.

Method 1: Upload URL and credential

Call the CreateUploadVideo operation and configure acceleration in the UserData parameter:

UserData={
  "AccelerateConfig": {
    "Type": "oss",
    "Domain": "https://oss-accelerate.aliyuncs.com"
  }
}

Method 2: STS token

Call the addFile method with the UserData property in the parmData parameter:

uploader.addFile(file,null,null,null,'{"Vod":{"UserData":{"AccelerateConfig":{"Type":"oss","Domain":"https://oss-accelerate.aliyuncs.com"}}}}');

UserData description

Name

Type

Required

Description

userData

string

No

Custom configurations such as callbacks and upload acceleration. Must be a JSON string.

The following table describes the parameters.

Parameter

Type

Description

Type

string

The upload acceleration type. Set to oss.

Domain

string

The accelerated domain name. HTTPS by default.

Note

An accelerated endpoint assigned after you enable upload acceleration is used, such as vod-*******.oss-accelerate.aliyuncs.com.

For more information about how to configure UserData, see Request parameter descriptions.

Stop an upload

Note

stopUpload takes effect only while a file is being uploaded.

uploader.stopUpload();

Manage a file list

Use the following operations to manage uploaded or in-progress files.

  • listFiles: Queries the upload list.

    Returns files added via addFile. The file property indicates the file type. Traverse the list to get file indexes for management operations.

    var list = uploader.listFiles();
    for (var i=0; i<list.length; i++) {
        console.log("file:" + list[i].file.name);
    }
  • deleteFile: Removes a file to be uploaded.

    uploader.deleteFile(index);//The index of the file that you want to delete. The index is returned by the listFiles operation.
  • cancelFile: Cancels the upload of a file.

    Note
    • After you call cancelFile, the oss is cancel as error message appears in the console. This prevents uploaded parts from occupying storage and incurring costs.

    • To resume a canceled upload, call uploader.resumeFile(index); to restore the file first.

    uploader.cancelFile(index);
  • resumeFile: Resumes the upload of a file.

    uploader.resumeFile(index);
  • cleanList: Clears the upload list.

    uploader.cleanList();

Resumable upload

If an upload fails due to a page crash or browser error, the SDK resumes from the breakpoint on re-upload and obtains the credential from the onUploadstarted callback. With Method 1: Upload URL and credential, call ApsaraVideo VOD API operations using videoId to get breakpoint information:

// The upload is started.
onUploadstarted: function (uploadInfo) {
  // If you use UploadAuth to upload the file, call the uploader.setUploadAuthAndAddress method.
  // If you use UploadAuth to upload the file, call different ApsaraVideo VOD API operations to obtain uploadAuth and uploadAddress based on whether uploadInfo.videoId has a value.
  // If uploadInfo.videoId has a value, call the RefreshUploadVideo operation. Otherwise, call the CreateUploadVideo operation.
  // Take note of the following information: An operation is directly called to obtain UploadAuth because this is a test demo. In actual scenarios, you must call a specific operation to obtain UploadAuth based on whether uploadInfo.videoId has a value.
  // If uploadInfo.videoId has a value, call the RefreshUploadVideo operation.
  // If uploadInfo.videoId is empty, call the CreateUploadVideo operation.
  if (!uploadInfo.videoId) {
    let createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
    axios.get(createUrl).then(({data}) => {
      let uploadAuth = data.UploadAuth
      let uploadAddress = data.UploadAddress
      let videoId = data.VideoId
      uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)                
    })
    self.statusText = 'The file upload is started...'
    console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  } else {
    // Display the breakpoint information.
    console.log(uploader.getCheckpoint(uploadInfo.file));
    // If the videoId parameter has a value, the video upload fails. The system resumes the upload from the breakpoint. You must refresh the upload credential based on the value of videoId.
    let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
    axios.get(refreshUrl).then(({data}) => {
      let uploadAuth = data.UploadAuth
      let uploadAddress = data.UploadAddress
      let videoId = data.VideoId
      uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
    })
  }
}

Obtain breakpoint information:

 uploader.getCheckpoint(file);

Exception handling

If an exception occurs, check the client upload SDK section in the Error codes topic to locate the cause.