All Products
Search
Document Center

ApsaraVideo VOD:Use the upload SDK for WeChat mini programs to upload files

Last Updated:Jan 09, 2024

Before you use the upload SDK for WeChat mini programs to upload files, you must integrate the SDK. This topic shows you how to integrate the upload SDK for WeChat mini programs and use the SDK to upload a file.

Upload a file

To upload a file by using the upload SDK for WeChat mini programs, perform the following steps:

  1. Import the JavaScript code.

    For more information about the download link of the JavaScript code, see Release notes of the upload SDK for mini programs.

    import VODUpload from 'aliyun-upload-sdk-1.0.0.min.js'
  2. Obtain an upload URL and an upload credential or an STS token for upload authorization.

    The upload SDK for WeChat mini programs supports the following two upload authorization methods:

    Upload result

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

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

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

    1. Declare a VODUpload initialization callback.

      Show code

      var uploader = new VODUpload({
             // The ID of your Alibaba Cloud account. This parameter cannot be left empty. To view the ID of your Alibaba Cloud account, go to the Account Center (https://account.console.aliyun.com/) by using your Alibaba Cloud account.             
             userId:"25346073170691****",
             // The ID of the region to which the file is uploaded. Default value: cn-shanghai. For more information about other region IDs such as eu-central-1 and ap-southeast-1, see Overview.
             region:"cn-shanghai",
             // 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 callback that is invoked if the upload starts.
            'onUploadstarted': function (uploadInfo) {
            },
            // The callback that is invoked if the upload is successful.
            'onUploadSucceed': function (uploadInfo) {
            },
            // The callback that is invoked if the upload fails.
            'onUploadFailed': function (uploadInfo, code, message) {
            },
            // The callback that is invoked if the default or custom upload progress is reached. The progress is measured in bytes.
            'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
            },
            // The callback that is invoked if the upload credential or STS token expires.
            'onUploadTokenExpired': function (uploadInfo) {
            },
            // The callback that is invoked if the entire file is 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.

      • (Recommended) Use the upload URL and credential

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

        Note

        If the upload credential expires, the onUploadTokenExpired callback is invoked. Call the resumeUploadWithAuth(uploadAuth) method to resume the upload by using a new upload credential.

        Show code

        // Start the upload.
        // The uploadInfo object specifies the information about the file that you want to upload.
        // {
        //   videoId: '', // The video or audio ID that is returned by the server. 
        //   Endpoint: '', // The public Object Storage Service (OSS) endpoint.
        //   Bucket: '', // The OSS bucket.
        //   Object: '' // The basic storage unit in OSS.
        // }
        'onUploadstarted': function (uploadInfo) {
          // The upload method. You must call different methods to obtain the upload URL and credential, depending on whether the uploadInfo.videoId parameter has a value. The upload SDK obtains the value of the uploadInfo.videoId parameter from the local storage.
          // If the uploadInfo.videoId parameter has a value, call the RefreshUploadVideo operation. Otherwise, call the CreateUploadVideo operation.
          // If the video that is being uploaded is deleted from the ApsaraVideo VOD console, a conflict occurs. Specifically, the video ID does not exist in the ApsaraVideo VOD console but exists in the browser. In this case, the InvalidVideo.NotFound error message is reported. You must clear the local storage.
          var url = '';
          if (uploadInfo.videoId) {
            // If the uploadInfo.videoId parameter has a value, call the RefreshUploadVideo operation.
            url = 'refreshUrl'; // The URL of the application server.
          }
          else{
            // If the uploadInfo.videoId parameter does not have a value, call the CreateUploadVideo operation.
            url = 'createUrl'; // The URL of the application server.
          }
        
          // The following sample code shows how to resume the upload by using the new upload credential.
          // The methods used to obtain the upload credential, upload URL, and video ID differ based on the application server.
          fetch(url)
            .then((res) => res.json())
            .then((data) => {
                uploader.setUploadAuthAndAddress(uploadInfo, data.UploadAuth, data.UploadAddress, data.VideoId);
          });
        },
        
        // The callback that is invoked if the upload credential expires.
        'onUploadTokenExpired': function (uploadInfo) {
          // During implementation, call the RefreshUploadVideo operation to obtain a new upload credential based on the uploadInfo.videoId parameter.
          // Set the uploadAuth parameter to the new upload credential obtained from ApsaraVideo VOD in the SDK.
        
          var url = 'refreshUrl'; // The URL of the application server.
          // The following sample code shows how to resume the upload by using the new upload credential.
          // The methods used to obtain the upload credential, upload URL, and video ID differ based on the application server.
          fetch(url)
            .then((res) => res.json())
            .then((data) => {
            uploader.resumeUploadWithAuth(data.UploadAuth);
          });
        },
      • Use the 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

        If the STS token expires, the onUploadTokenExpired callback is invoked. Call the resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken); method to resume the upload by using a new STS token.

        Show code

        onUploadstarted: function (uploadInfo) {
          // If you use the STS token, call the uploader.setUploadAuthAndAddress method.
          var stsUrl = 'stsUrl';
          // The following sample code shows how to resume the upload by using the new STS token.
          // The methods used to obtain the AccessKey ID, AccessKey secret, and STS token differ based on the application server.
          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 the STS token expires, you must obtain a new STS token to resume the upload.
          // If the file to be uploaded is large in size, the STS token may expire during the upload. In this case, you must call the resumeUploadWithSTSToken method in the onUploadTokenExpired callback to resume the upload by using a new STS token.
        
          var stsUrl = 'stsUrl';
          // The following sample code shows how to resume the upload by using the new STS token.
          // The methods used to obtain the AccessKey ID, AccessKey secret, and STS token differ based on the application server.
          fetch(stsUrl)
            .then((res) => res.json())
            .then((data) => {
            var info = data.SecurityTokenInfo
            uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
          });
        },
  4. Set upload parameters based on the type of the file that you want to upload. The file can be an audio file, a video file, or an image file.

    Upload parameters for audio and video files

    Set the upload parameters for adding an audio or video file to the upload list.

        wx.chooseVideo({
            success: function (res) {
                var file = {url: res.tempFilePath, coverUrl: res.thumbTempFilePath};
                var userData = '{"Vod":{}}';
                uploader.addFile(file, null, null, null, userData)
            }
        })

    During the upload, you can use paramData to customize audio and video information. paramData is a JSON string. You must set Vod at the first layer. Add attributes that paramData supports within Vod. For more information about supported attributes, see CreateUploadVideo. Sample code:

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

    Upload parameters for image files

    Set the upload parameters for adding an image file to the upload list.

        wx.chooseImage({
            success: function (res) {
                var file = {url: res.tempFilePath, coverUrl: res.thumbTempFilePath};
                var userData = '{"Vod":{}}';
                uploader.addFile(file, null, null, null, userData)
            }
        })
  5. Start the upload.

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

      uploader.startUpload();
    2. When the upload starts, the onUploadProgress callback is invoked to synchronize the upload progress.

    3. When the file is uploaded, the onUploadSucceed callback is invoked to return the upload result.

Upload result

  • After a video is uploaded, the videoId parameter is returned, which indicates the video ID. Then, you can obtain the streaming URL based on the video ID to play the video. For more information, see Use playback credentials to play videos.

  • After an image is uploaded, the imageUrl parameter is returned. The value of the imageUrl parameter indicates the image URL. If URL signing is enabled, the image URL expires after a specific period of time. For more information, see Configure URL signing.

Manage the upload list

  • Remove a file to be uploaded.

    The index parameter indicates the index of a file in the list returned by the listFiles method.

    uploader.deleteFile(index);
  • Cancel the upload of a single file.

    uploader.cancelFile(index);
    Note

    You can use this method to cancel the upload of a file that is being uploaded or waiting to be uploaded.

  • Resume the upload of a single file.

    uploader.resumeFile(index);
  • Query the upload list.

    uploader.listFiles();
  • Clear the upload list.

    uploader.cleanList();

Manage the upload credential or STS token

  • Resume the upload after the upload credential expires.

    uploader.resumeUploadWithAuth(uploadAuth);
  • Specify the upload URL and credential.

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

    uploader.setUploadAuthAndAddress(uploadInfo,uploadAuth, uploadAddress, videoId);
  • Specify the STS token.

    Specify the STS token in the onUploadstarted callback. uploadInfo is included in the callback.

    uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
  • Resume the upload after the STS token expires.

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

References

Audio and video playback

ApsaraVideo Player SDK for Web