All Products
Search
Document Center

ApsaraVideo VOD:Upload SDK for JavaScript

Last Updated:Dec 25, 2023

This topic describes how to integrate the upload SDK for JavaScript and use the SDK to upload local or online files from clients to ApsaraVideo VOD.

Prerequisites

  • The system settings required for the upload, including the storage path in the specified region and the callback settings, are configured. For more information, see Manage storage buckets and Configure callbacks.

  • A RAM user is created and used to access ApsaraVideo VOD. To prevent security risks caused by the leakage of the AccessKey pair of your Alibaba Cloud account, we recommend that you create a RAM user and grant the RAM user the permissions required to access ApsaraVideo VOD. Then, you can use the AccessKey pair of the RAM user to access ApsaraVideo VOD. For more information, see Create and grant permissions to a RAM user.

  • The upload SDK for JavaScript can be used in the following browsers:

    • Internet Explorer 10 and later

    • Edge

    • Major versions of Google Chrome, Firefox, or Safari

    • Major versions of the default browsers provided by Android, iOS, or Windows Phone

  • Download links: Upload SDK for JavaScript V1.5.6 and demo source code (jquery and Vue)

Upload processes

Client upload SDKs encapsulate the logic of uploading files to OSS buckets. When you upload medial files from clients, the files are directly uploaded to OSS buckets allocated by ApsaraVideo VOD without forwarding by servers. Therefore, the clients must be authenticated. You must deploy an authorization service on your application server to obtain upload URLs and credentials. Client upload SDKs support authorization based on upload credentials and authorization based on STS tokens. We recommend that you use an upload credential. For more information, see Comparison between credentials and STS.

Process of uploading a media file by using an upload URL and an upload credential

The following figure shows the complete process of uploading a media file by using an upload URL and an upload credential. In this example, ApsaraVideo VOD SDK is integrated to obtain the upload URL and credential.客户端SDK上传凭证上传流程

  1. A user deploys an authorization service on an application server, such as ApsaraVideo VOD SDK, to obtain upload URLs and credentials.

  2. A client sends a request to the application server to request an upload URL and an upload credential.

  3. The application server sends a request to ApsaraVideo VOD to request the upload URL and credential.

  4. ApsaraVideo VOD returns the upload URL and credential.

    Note

    ApsaraVideo VOD also generates media IDs, which can be used in media lifecycle management and media processing.

    • For a video, the media ID is returned in the VideoId parameter.

    • For an image, the media ID is returned in the ImageId parameter.

    • For an auxiliary media asset, the media ID is returned in the MediaId parameter.

    • Properly keep the returned media IDs, which are required in subsequent tasks, such as media asset management, audio and video playback, and media processing.

  5. The application server returns the upload URL and credential to the client.

    Note

    The application server does not need to perform Base64 decoding on the upload URL or credential.

  6. The client uses the upload URL and credential to initialize an upload instance.

  7. The client constructs upload parameters to send an upload request.

  8. OSS returns the upload result.

    Note

    You can also set callbacks in advance to receive notifications about upload events.

Process of uploading a media file by using an STS token

If you use authorization based on the STS token, you must create a RAM role and grant the RAM role permissions to access ApsaraVideo VOD. For more information, see Use STS to upload videos.

The following figure shows the complete process of uploading a media file by using an STS token.客户端STS方式上传流程

  1. A user deploys an authorization service on an application server, such as ApsaraVideo VOD SDK, to obtain temporary STS tokens.

  2. A client sends a request to the application server to request an STS token.

  3. The application server sends a request to STS to request the STS token.

  4. STS returns the token.

  5. The application server returns the STS token to the client.

  6. The client uses the STS token to initialize an upload instance.

  7. The client constructs upload parameters to send an upload request.

  8. OSS returns the upload result.

    Note

    You can also set callbacks in advance to receive notifications about upload events.

Set the upload credential or STS token

Note

This section describes how to set the upload credential for audio and video files. To obtain an image upload credential, call the CreateUploadImage operation.

  • Set the upload URL and credential

    Set the upload URL and credential in the onUploadstarted callback. uploadInfo is included in the callback.

    const {VideoId,UploadAuth,UploadAddress} = data;
    uploader.setUploadAuthAndAddress(uploadInfo,UploadAuth,UploadAddress,VideoId);

    Parameter

    Description

    uploadInfo

    The value can be obtained from the first parameter in the onUploadstarted callback.

    uploadAuth

    The value can be obtained from the response to the CreateUploadVideo operation.

    uploadAddress

    The value can be obtained from the response to the CreateUploadVideo operation.

    videoId

    The value can be obtained from the response to the CreateUploadVideo operation.

  • Resume the upload after the upload credential expires

    Call the resumeUploadWithAuth operation in the onUploadTokenExpired callback to resume the upload after the upload credential expires. Set uploadAuth to the new upload credential returned in the response to the RefreshUploadVideo operation.

    const {VideoId,UploadAuth,UploadAddress} = data;
    uploader.resumeUploadWithAuth(UploadAuth);
  • Set the STS token

    Call setSTSToken to set the STS token for file upload. Call setSTSToken in the onUploadstarted callback. uploadInfo is included in the callback.

    var info = data.SecurityTokenInfo
    uploader.setSTSToken(uploadInfo,info.AccessKeyId,info.AccessKeySecret,info.SecretToken);

    Parameter

    Description

    uploadInfo

    The value can be obtained from the first parameter in the onUploadstarted callback.

    accessKeyId

    The value can be obtained from the response to the CreateSecurityToken operation.

    accessKeySecret

    The value can be obtained from the response to the CreateSecurityToken operation.

    secretToken

    The value can be obtained from the response to the CreateSecurityToken operation.

  • Resume the upload after the STS token expires

    Call resumeUploadWithSTSToken in the onUploadTokenExpired callback to update the upload credential after it expires.

    var info = data.SecurityTokenInfo
    uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);

Upload a file

Perform the steps described in this section to upload a file by using the upload SDK for JavaScript.

Note
  • If the upload on the web client is interrupted, a 404 error may occur when you try to re-upload the file. You can update the upload SDK to V1.5.3 or later and re-upload the file. If you use the upload SDK for JavaScript that is earlier than V1.5.3, rename the file before you re-upload the file to prevent errors.

  • If you want to upload multiple files at the same time, you can create multiple upload instances. Each upload instance represents an upload task for a single file. You cannot use an upload instance to upload multiple files at the same time.

  1. Integrate the upload SDK for JavaScript.

    Download the upload SDK for JavaScript package. For more information, see SDK overview and download. The upload SDK provides only partial support for external modules. If you call the import or require method to reference files, the ReferenceError: OSS is not defined error message is returned. You can use one of the following methods to reference files based on your business requirements:

    • (Recommended) Reference by using scripts in HTML

      <!--  The es6-promise file is required for Internet Explorer. Internet Explorer 10 and later versions 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.5.min.js"></script>
    • Reference by using a module

      You can manually add an Object Storage Service (OSS) module to the window. Sample code:

      Note

      If you have already referenced files on the HTML page by using scripts, you do not need to add the module.

      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.5.min'
  2. Obtain an upload URL and an upload credential or an STS token for upload authorization.

    If you use the upload SDK for JavaScript to upload a file, you must obtain an upload credential from AppServer and upload the file to the OSS server on Alibaba Cloud. After you obtain the upload credential from AppServer, specify the credential in the configurations of the SDK. You can use one of the following methods to obtain an upload credential:

    Upload result

    Use the obtained upload URL and credential or the obtained STS token to initialize the upload instance.

  3. Initialize the upload instance by using an upload credential or an STS token. We recommend that you use an upload credential to initialize the upload instance.

    You need to configure the initialization callback before you initialize the upload instance.

    1. Configure the initialization callback.

      Configure a callback for AliyunUpload.Vod. The following sample code provides an example of the configurations that you can specify when you initialize the upload instance:

      Note

      For more information about the supported regions of ApsaraVideo VOD and the corresponding endpoints, see Region IDs of ApsaraVideo VOD.

      Show code

      var uploader = new AliyunUpload.Vod({
           // The account ID. This parameter is required. To view your account ID, log on to the Alibaba Cloud Management Console and go to the Account Center (https://account.console.aliyun.com/).
           userId:"122",
           // The region in which you want to upload the file. Default value: cn-shanghai. 
           // eu-central-1, ap-southeast-1
           region:"",
           // The size of each part in multipart upload. Unit: bytes. The default size is 1 MB (1024 × 1024). The size cannot be smaller than 100 KB (100 × 1024).
           partSize: 1048576,
           // The maximum number of parts that can be uploaded in parallel. Default value: 5.
           parallel: 5,
           // The maximum number of attempts to retry the upload when a network error occurs. Default value: 3.
           retryCount: 3,
           // The interval at which you want the system to retry the upload when a network error occurs. Default value: 2. Unit: seconds.
           retryDuration: 2,
           // The upload starts.
           'onUploadstarted': function (uploadInfo) {
            },
           // The file is uploaded.
           '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){
             }
        });
    2. Initialize an upload instance. You can use an upload URL and an upload credential or an STS token to initialize the upload instance based on your business requirements.

      Obtain or update the upload credential in the onUploadstarted callback. Use one of the following methods to initialize the upload instance based on your business requirements:

      • (Recommended) Use an upload URL and an upload credential

        Specify the upload URL and credential by calling the setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress,videoId) method in the onUploadStarted callback that is fired when the upload starts.

        Sample code for uploading an audio or video file

        Note

        The onUploadTokenExpired callback is fired when the upload credential expires. Call the resumeUploadWithAuth(uploadAuth) method to set a new credential and resume the upload.

        Show code

        // Start the upload.
        // uploadInfo contains the information about the file that you want to upload.
        // {
        //   videoId: '', // The ID of the video or audio file. The ID is returned by the server.
        //   Endpoint: '', // The endpoint that is used to access OSS.
        //   Bucket: '', // The OSS bucket.
        //   Object: ''// The basic unit for storing data in OSS.
        // }
        'onUploadstarted': function (uploadInfo) {
          // The upload method. You can call different operations in ApsaraVideo VOD to obtain uploadauth and uploadAddress based on whether uploadInfo.videoId is empty. The SDK obtains the value of uploadInfo.videoId from localstorage.
          // If the uploadInfo.videoId parameter is not empty, call the RefreshUploadVideo operation. Otherwise, call the CreateUploadVideo operation.
          // If you delete a video or audio file from the ApsaraVideo VOD console during the upload, the video ID no longer exists in the console but exists in the browser. In this case, the error InvalidVideo.NotFound is returned. To resolve this issue, you must clear the value of localstorage.
          var url = '';
          if (uploadInfo.videoId) {
            // If the uploadInfo.videoId parameter is not empty, call the RefreshUploadVideo operation.
            url = 'refreshUrl'; // Specify the URL that is used to access AppServer.
          }
          else{
            // If the uploadInfo.videoId parameter is empty, call the CreateUploadVideo operation.
            url = 'createUrl'; // Specify the URL that you use to call the CreateUploadVideo operation. Example: https://xxxx.com/createUploadVideo.
          }
        
          // The following sample code provides an example on how to set the upload credential:
          // The logic used to obtain UploadAuth, UploadAddress, and VideoId may vary based on AppServer.
          fetch(url)
            .then((res) => res.json())
            .then((data) => {
                uploader.setUploadAuthAndAddress(uploadInfo, data.uploadAuth, data.uploadAddress, data.videoId);
          });
        },
        
        // The upload credential expires.
        'onUploadTokenExpired': function (uploadInfo) {
          // Call the RefreshUploadVideo operation to update uploadAuth based on the value of uploadInfo.videoId.
          // Specify the new value of the uploadAuth parameter obtained from ApsaraVideo VOD in the SDK.
        
          // Update uploadAuth that you obtained from ApsaraVideo VOD to the upload SDK for JavaScript.
          // The following sample code provides an example on how to set the upload credential:
          // The logic used to obtain UploadAuth, UploadAddress, and VideoId may vary based on AppServer.
          fetch(url)
            .then((res) => res.json())
            .then((data) => {
            uploader.resumeUploadWithAuth(data.UploadAuth);
          });
        },

        Sample code for uploading an image

        Note

        The upload credential is not automatically updated when you upload an image. After the upload credential expires, the ImageId becomes invalid and can be deleted. In this case, you must obtain a new credential to upload the image.

        Show code

        // Start the upload.
        // uploadInfo contains the information about the file that you want to upload.
        // {
        // ImageId: ''', // The ID of the image. The ID is returned by the server.
        //   Endpoint: '', // The endpoint that is used to access OSS.
        //   Bucket: '', // The OSS bucket.
        //   Object: ''// The basic unit for storing data in OSS.
        // }
        'onUploadstarted': function (uploadInfo) {
          // The upload method. You can call different operations in ApsaraVideo VOD to obtain uploadauth and uploadAddress based on whether uploadInfo.ImageId is empty. The SDK obtains the value of uploadInfo.ImageId from localstorage.
          // If you delete an image file from the ApsaraVideo VOD console during the upload, the image ID no longer exists in the console but exists in the browser. In this case, the error NotFound is returned. To resolve this issue, you must clear the value of localstorage.
          var url = 'createUrl';   // Specify the URL that you use to call the CreateUploadVideo operation. Example: https://xxxx.com/createUploadImage.
          // The logic used to obtain UploadAuth, UploadAddress, and ImageId may vary based on AppServer.
          fetch(url)
            .then((res) => res.json())
            .then((data) => {
                uploader.setUploadAuthAndAddress(uploadInfo, data.UploadAuth, data.UploadAddress, data.ImageId);
          });
        }
        
      • Use an STS token

        Specify the obtained STS token by calling the setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken); method in the onUploadStarted callback that is fired when the upload starts.

        Note

        The onUploadTokenExpired callback is fired when the STS token expires. Call the resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken) method to set a new STS token and resume the upload.

        Show code

        onUploadstarted: function (uploadInfo) {
          // If you use an STS token to upload the file, you must call the uploader.setUploadAuthAndAddress method.
          var stsUrl = 'stsUrl';
          // The following sample code provides an example on how to set the upload credential:
          // The logic used to obtain accessKeyId, accessKeySecret, and secretToken may vary based on AppServer.
          fetch(stsUrl)
            .then((res) => res.json())
            .then((data) => {
            var info = data.SecurityTokenInfo
            uploader.setSTSToken(uploadInfo, info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
          });
        },
        
        onUploadTokenExpired: function (uploadInfo) {
          // If you use an STS token to upload a file and the token expires during the upload, obtain a new STS token and resume the upload.
          // If you upload a large file, the STS token may expire before the upload is complete. In this case, call the resumeUploadWithSTSToken method in the onUploadTokenExpired callback.
        
          var stsUrl = 'stsUrl';
          // The following sample code provides an example on how to set the upload credential:
          // The logic used to obtain accessKeyId, accessKeySecret, and secretToken may vary based on AppServer.
          fetch(stsUrl)
            .then((res) => res.json())
            .then((data) => {
            var info = data.SecurityTokenInfo
            uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
          });
        },
  4. Configure the parameters for the upload based on the type of the file that you want to upload.

    1. Select a file that you want to upload.

       <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.
          }
        });
    2. Add the selected file to the upload list.

      uploader.addFile(file,null,null,null,'{"Vod":{}}');

      Parameter

      Required

      Type

      Description

      file

      Yes

      File

      The video or audio file that you want to upload.

      endpoint

      No

      String

      The OSS endpoint. Specify the OSS endpoint based on the region in which you want to upload the file. If you specify null, the file is uploaded to an endpoint selected by AppServer.

      bucket

      No

      String

      The bucket to which you want to upload the file. If you specify null, the file is uploaded to a bucket selected by AppServer.

      object

      No

      String

      The object to which you want to upload the file. If you specify null, the actual value is determined by AppServer.

      paramData

      No

      String

      The information about the video or audio file that you want to upload such as the title and description of the video or audio file and transcoding and callback settings for the video or audio file. You can specify paramData if you use an STS token to upload a video or audio file to ApsaraVideo VOD.

      The value of paramData is a JSON string. You must specify Vod in the request. You can nest parameters that are supported by the paramData parameter under Vod. For more information, see CreateUploadVideo or CreateUploadImage.

      Sample code:

      Note
      • You must specify paramData for the SDK only if you use an STS token to upload a file. If you use an upload URL and an upload credential to upload a file, specify paramData only when you call the CreateUploadVideo or CreateUploadImage operation.

      • If you specify both the WorkflowId and TemplateGroupId, the value of the WorkflowId parameter takes effect.

      • Specify the title and category ID of the video or audio file.

        var paramData = '{"Vod":{"Title":"test","CateId":"234"}}';
      • Specify the title of the video or audio file and the ID of the transcoding template group.

        var paramData = '{"Vod":{"Title":"test","TemplateGroupId":"e6bb587b5365ac38a41462a4940****"}}';
      • Specify the title of the video or audio file and the ID of the workflow.

        var paramData = '{"Vod":{"Title":"test","WorkflowId":"e2d027f16b5ee9cdf126266d32d****"}}';
  5. Start the upload.

    1. Call the startUpload() method to start the upload.

      uploader.startUpload();
    2. Fire the onUploadProgress callback to synchronize the upload progress when the upload starts.

    3. Fire the onUploadSucceed callback to return the upload result when the file is uploaded.

Upload result

  • After a video or audio file is uploaded, videoId is returned. Then, you need to obtain a playback URL to play the file. For more information, see Use playback credentials to play videos.

  • imageUrl is not automatically returned when an image is uploaded. To obtain the image URL, configure a callback for the ImageUploadComplete event before you upload images. You can obtain the FileURL in the ImageUploadComplete callback. For more information, see Configure callbacks. If you have enabled URL signing, the URL expires after the validity period elapses. For more information, see Configure URL signing.

Advanced features

Upload management

Stop the upload

Note

You can call stopUpload only when a file is being uploaded. Otherwise, the API operation does not take effect.

uploader.stopUpload();

Queue management

You can call the following API operations to manage files that are uploaded or being uploaded. The following section describes the API operations that are supported.

  • listFiles

    The returned data contains information about the files that are uploaded by calling addFile. The file property in the returned data indicates the file type. You can traverse the list to obtain the indexes of the files that you want to manage.

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

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

    Note
    • After cancelFile is called, the oss is cancel as error message is displayed in the console. This prevents the uploaded parts from occupying the storage space and reduces storage costs.

    • If you want to resume the upload after you cancel a upload, you must use uploader.resumeFile(index); to restore the file before you resume the upload.

    uploader.cancelFile(index);
  • resumeFile

    uploader.resumeFile(index);
  • cleanList

    uploader.cleanList();

Resumable upload

If errors such as forceful page shutdown and browser breakdown occur during file upload and you try to re-upload the file, the upload SDK for JavaScript resumes the upload from the breakpoint and obtains the upload credential from the onUploadstarted callback. If you use the upload URL and credential to upload the file, call API operations in ApsaraVideo VOD to obtain breakpoint information based on the value of videoId. Sample code:

onUploadstarted: function (uploadInfo) {
if (Upload method 1) {
  if(!uploadInfo.videoId)// No error occurred during file upload.
  {
    // Call the CreateUploadVideo operation in your environment.
    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
  }
  else// If the videoId parameter is not empty, update the upload credential based on the value of videoId.
  {
    // Call the RefreshUploadVideo operation in your environment to update the upload credential.
    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
  }
}
else(Upload method 2)
{
   // Call the setSTSToken operation to obtain the STS token in your environment.
   uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
}
}

You can call the following method to obtain the breakpoint information:

 uploader.getCheckpoint(file);