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

  • ApsaraVideo VOD is activated. For more information, see Activate ApsaraVideo VOD.

  • 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 VOD storage 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.
  • Optional. A role is created for the RAM user and the role is granted the permissions required to access ApsaraVideo VOD if you want to access ApsaraVideo VOD by using Security Token Service (STS). For more information, see Create a RAM role and grant temporary access permissions to the role by using STS.
    Note For more information about the scenarios in which STS can be used, see Comparison between credentials and STS.
  • The file to be uploaded is selected by using the standard input method. The size of the file to be uploaded cannot exceed 10 GB. If the file size exceeds 10 GB, resumable upload is used. For more information, see Advanced feature.
  • 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

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 upload the file again. You can update the upload SDK to V1.5.3 or later and upload the file again. If you use the upload SDK for JavaScript that is earlier than V1.5.3, rename the file before you upload the file again 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. For more information, see SDK 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-vod-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. The following sample code provides an example:
      Note If you have already referenced files in 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:

    Verify the 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 describes 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 VOD centers and endpoints.
      var uploader = new AliyunUpload.Vod({
             // The account ID. This parameter is required. You can log on to the Alibaba Cloud Management Console and go to the Account Center (https://account.console.aliyun.com/) to view your account ID.
             userId:"122",
           // The region to which you want to upload the file. Default value: cn-shanghai. 
           // eu-central-1, ap-southeast-1
           region:"",
             // The size of each part when you upload a file in parts. Default value: 1 MB. 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 that can be performed to retry the upload when a network error occurs. Default value: 3.
           retryCount: 3,
           // The intervals 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 the 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.

        Important The onUploadTokenExpired callback is fired when the upload credential expires. Call the resumeUploadWithAuth(uploadAuth) method to set a new credential and resume the upload.
        // Start the upload.
        // uploadInfo contains the information about the file to be uploaded.
        // {
        //   videoId: '', // The ID of the video or audio file. The ID is returned by ApsaraVideo VOD.
        //   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 in 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 you want to use to access AppServer.
          }
          else{
            // If the uploadInfo.videoId parameter is empty, call the CreateUploadVideo operation.
            url = 'createUrl'; // Specify the URL that you want to use to access AppServer.
          }
        
          // 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.
          // Update uploadAuth that you obtained from ApsaraVideo VOD to the upload SDK for JavaScript.
        
          var url = 'refreshUrl'; // Specify the URL that you want to use to access AppServer.
          // 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);
          });
        },
      • 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.

        Important 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.
        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. 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. Specify 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":{}}');
      ParameterRequiredTypeDescription
      fileYesFileThe video or audio file to be uploaded.
      endpointNoStringThe OSS endpoint. Specify the OSS endpoint based on the region to which you want to upload the file. If you specify null, the file is uploaded to an endpoint selected by AppServer.
      bucketNoStringThe bucket to which you want to upload the file. If you specify null, the file is uploaded to a bucket selected by AppServer.
      objectNoStringThe object to which you want to upload the file. If you specify null, the actual value is determined by AppServer.
      paramDataNoStringThe 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 this parameter 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.
      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 when you call the CreateUploadVideo operation.
      • If both the WorkflowId and TemplateGroupId parameters are set, 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.
    Note You can upload only a video or audio file from a client.
    1. Call the startUpload() method to start the upload.
      uploader.startUpload();
    2. Fire the onUploadProgress callback to synchronize the upload progress after the upload starts.
    3. Fire the onUploadSucceed callback to return the upload result if 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 after an image is uploaded. To obtain the image URL, configure a callback for the ImageUploadComplete event before you upload images. You can obtain 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 authentication .

Manage the upload list

You can call the following API operations to manage files that are uploaded or being uploaded. The following table 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 to be deleted. 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 re-upload the file after you cancel the upload, you must use uploader.resumeFile(index); to restore the file before you re-upload the file.
    uploader.cancelFile(index);
  • resumeFile
    uploader.resumeFile(index);
  • cleanList
    uploader.cleanList();

Set the upload credential or STS token

  • 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);
    ParameterDescription
    uploadInfoThe value can be obtained from the first parameter in the onUploadstarted callback.
    uploadAuthThe value can be obtained from the response to the CreateUploadVideo operation.
    uploadAddressThe value can be obtained from the response to the CreateUploadVideo operation.
    videoIdThe 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);
    ParameterDescription
    uploadInfoThe value can be obtained from the first parameter in the onUploadstarted callback.
    accessKeyIdThe value can be obtained from the response to the CreateSecurityToken operation.
    accessKeySecretThe value can be obtained from the response to the CreateSecurityToken operation.
    secretTokenThe 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 management

Stop the upload

Note You can call stopUpload only when a file is being uploaded. Otherwise, the API operation does not work.
uploader.stopUpload();

Advanced feature

Resumable upload

If errors such as forceful page shutdown and browser breakdown occur during file upload and you try to upload the file again, 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);