All Products
Search
Document Center

ApsaraVideo VOD:Use the upload SDK for Android to upload files

Last Updated:Jan 15, 2024

You can upload a media file to ApsaraVideo VOD. The media file can be a local file or an online file. VODUploadClient is an upload instance that is used to upload media files from an Android device. After a video is uploaded, the videoId parameter is returned. The value of the videoId parameter indicates the video ID. Then, you must obtain a streaming URL based on the video ID to play the video. This topic describes how to upload a media file by using the upload SDK for Android.

Prerequisites

The upload SDK for Android is integrated. For more information, see Integrate the upload SDK for Android.

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.

Upload a file

Perform the following steps to upload a file from an Android device:

  1. Obtain an upload URL and an upload credential or a Security Token Service (STS) token.

  2. Initialize the upload instance by using the obtained upload credential or STS token.

  3. Configure callbacks to receive key messages during the upload.

  4. Construct upload parameters based on the type of the file to be uploaded. You can upload audio, video, or image files.

  5. Start the upload.

Note

The upload parameters for images are slightly different from those for audio and video files. Auxiliary media assets cannot be uploaded from a client.

Step 1: Obtain authorization for the upload

Two authorization methods are provided for the client upload SDKs of ApsaraVideo VOD: by using an upload URL and an upload credential and by using an STS token. For more information, see Comparison between credentials and STS.

Execution result

The obtained upload URL and credential or STS token is used as input to initialize the upload instance.

Step 2: Initialize the upload instance

Use the upload URL and credential or STS token to initialize the upload instance based on your business needs.

(Recommend) Method 1: Initialize the upload instance by using the upload URL and credential

1. Declare the initialization callback for the upload instance VODUploadClient.

uploader = new VODUploadClientImpl(getApplicationContext());

2. Initialize the upload instance VODUploadClient.

Note
  • If you use the upload URL and credential, call the init method to initialize the upload instance.

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

  • If the upload URL and credential expire when you use them to upload an audio or video file, the onUploadTokenExpired callback is fired. Call the resumeWithAuth(uploadAuth) method to resume the upload by using a new upload credential.

Show code

// create VODUploadClient
final VODUploadClient uploader = new VODUploadClientImpl(getApplicationContext());
// setup callback
VODUploadCallback callback = new VODUploadCallback(){
    @Override
    public void onUploadSucceed(UploadFileInfo info) {
        OSSLog.logDebug("onsucceed ------------------" + info.getFilePath());
    }

    @Override
    public void onUploadFailed(UploadFileInfo info, String code, String message) {
        OSSLog.logError("onfailed ------------------ " + info.getFilePath() + " " + code + " " + message);
    }

    @Override
    public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
        OSSLog.logDebug("onProgress ------------------ " + info.getFilePath() + " " + uploadedSize + " " + totalSize);
    }

    @Override
    public void onUploadTokenExpired() {
        OSSLog.logError("onExpired ------------- ");
        // Call the RefreshUploadVideo operation to update the upload credential. 
        uploadAuth = "The new upload credential";
        uploader.resumeWithAuth(uploadAuth);
    }

    @Override
    public void onUploadRetry(String code, String message) {
        OSSLog.logError("onUploadRetry ------------- ");
    }

    @Override
    public void onUploadRetryResume() {
        OSSLog.logError("onUploadRetryResume ------------- ");
    }

    @Override
    public void onUploadStarted(UploadFileInfo uploadFileInfo) {
        OSSLog.logError("onUploadStarted ------------- ");
        // The value of the uploadAuth parameter is the upload credential and the value of the uploadAddress parameter is the upload URL. 
        uploader.setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress);
    }
};
// Initialize the upload instance.
uploader.init(callback);

Method 2: Initialize the upload instance by using the STS token

1. Declare the initialization callback for the upload instance VODUploadClient.

uploader = new VODUploadClientImpl(getApplicationContext());

2. Initialize the upload instance VODUploadClient.

Note
  • If you use the STS token, call the init(accessKeyId, accessKeySecret, secretToken, expireTime, callback) method to initialize the upload instance.

  • Set the initialization parameter secretToken to the obtained STS token.

  • If the STS token expires, the OnUploadTokenExpired callback is fired. Call the resumeWithToken(accessKeyId, accessKeySecret, secretToken, expireTime) method to resume the upload by using a new STS token.

Show code

// create VODUploadClient object
uploader = new VODUploadClientImpl(getApplicationContext());
// setup callback
// setup callback
VODUploadCallback callback = new VODUploadCallback() {
            public void onUploadSucceed(UploadFileInfo info) {
                OSSLog.logDebug("onsucceed ------------------" + info.getFilePath());
            }
            public void onUploadFailed(UploadFileInfo info, String code, String message) {
                OSSLog.logError("onfailed ------------------ " + info.getFilePath() + " " + code + " " + message);
            }
            public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
                OSSLog.logDebug("onProgress ------------------ " + info.getFilePath() + " " + uploadedSize + " " + totalSize);
                    }
                }
            }
            public void onUploadTokenExpired() {
                OSSLog.logError("onExpired ------------- ");
                    // Call the resumeWithToken method after a new STS token is obtained.
                    uploader.resumeWithToken(accessKeyId, accessKeySecret, secretToken, expireTime);
            }
            public void onUploadRetry(String code, String message) {
                OSSLog.logError("onUploadRetry ------------- ");
            }
            public void onUploadRetryResume() {
                OSSLog.logError("onUploadRetryResume ------------- ");
            }
            public void onUploadStarted(UploadFileInfo uploadFileInfo) {
                OSSLog.logError("onUploadStarted ------------- ");
            }
        };
// Initialize the upload instance. If the STS token expires, the onUploadTokenExpired callback is fired. Call the resumeWithToken method to resume the upload by using a new STS token. By default, resumable upload is supported.
uploader.init(accessKeyId, accessKeySecret, secretToken, expireTime, callback);

Step 3: Set the class for upload status callbacks

Set the VODUploadCallback object. The object belongs to the class for upload status callbacks. You must set the following callback methods:

Show code

/**
 This callback is fired when the upload succeeds.
 @param info The information about the file that you upload.
 */
void onUploadSucceed(UploadFileInfo info);
/**
 This callback is fired when the upload fails.
 @param info The information about the file that you upload.
 @param code The error code.
 @param message The error message.
 */
 void onUploadFailed(UploadFileInfo info, String code, String message);
/**
 This callback is fired when the default or custom upload progress is reached.
 @param fileInfo The information about the file that you upload.
 @param uploadedSize The size of uploaded parts.
 @param totalSize The total size of the file that you upload.
 */
 void onUploadProgress(UploadFileInfo fileInfo, long uploadedSize, long totalSize);
/**
 This callback is fired when the upload URL and credential expire.
 If you use the upload URL and credential to upload a file, call the resumeWithAuth method to resume the upload.
 If you use STS tokens to upload media files, call the resumeWithToken method to resume the upload.
 */
 void onUploadTokenExpired();
/**
 This callback is fired when the system retries the upload.
 */
 void onUploadRetry(String code, String message);
/**
 This callback is fired when the system resumes the upload after the upload retry is complete.
 */
 void onUploadRetryResume ();
/**
 This callback is fired when the upload starts.
 If you use the upload URL and credential to upload a file, call the setUploadAuthAndAddress:uploadAuth:uploadAddress: method to specify the upload URL and credential.
 @param fileInfo The information about the file that you upload.
 */
  void onUploadStarted(UploadFileInfo fileInfo);

Step 4: Construct an upload request function

Parameters for audio or video files

Construct an upload request function to add an audio or video file to the upload list.

String filePath = "Path of the file";
VodInfo vodInfo = new VodInfo();
vodInfo.setTitle("Title" + index);
vodInfo.setDesc("Description" + index);
vodInfo.cateId (19);
vodInfo.tags("sports");
uploader.addFile(filePath,vodInfo);

Parameters for image files

Construct an upload request function to add an image file to the upload list.

String filePath = "Path of the image";
VodInfo vodInfo = new VodInfo();
vodInfo.setTitle("Title" + index);
vodInfo.setDesc("Description" + index);
vodInfo.cateId (19);
vodInfo.tags("sports");
uploader.addFile(filePath,vodInfo);

Description on vodInfo

// The title.
String title;
// The tags.
List tags;
// The description.
String desc;
// The category ID.
idInteger cateId;
// The URL of the thumbnail. The value must be a complete URL that starts with https://.
String coverUrl;
Note

After you add a file to be uploaded, the SDK encapsulates the file in an UploadFileInfo object that has the following structure:

// The local path of the file.
String filePath;
//endpoint
String endpoint;
//bucket
String bucket;
//object
String object;
//VodInfo
VodInfo vodInfo;

Step 5: Start the upload

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

    void start();

    When this method is called, the onUploadStarted callback is fired. If you use an upload URL and credential to upload a file, specify the upload URL and credential in this callback. Sample code:

    void setUploadAuthAndAddress(UploadFileInfo uploadFileInfo, String uploadAuth, String uploadAddress)

  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. The callback parameters include videoId and imageUrl.

Execution result

  • After a video is uploaded, the videoId parameter is returned. The value of the videoId parameter indicates the video ID. Then, you must obtain the streaming URL 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.

Advanced features

Queue management

The upload instance VODUploadClient allows you to add multiple files to be uploaded in sequence. You can use the following methods to manage the upload list:

Note

The VODUploadClient object allows you to upload multiple files at a time. However, if you use upload URLs and credentials to upload media files, you must separately set the configuration for each file. The code for uploading multiple files at a time is complex. Therefore, we recommend that you add a single file to the upload list at a time.

  • Remove a file from the upload list. If the file to be removed is being uploaded, the system cancels the upload and automatically starts to upload the next file in the list.

    void deleteFile(int index)
  • Clear the upload list. If a file in the list is being uploaded, the system cancels the upload.

    void clearFiles()
  • Query the upload list.

    List<UploadFileInfo> listFiles()
  • Mark a file in the upload list as canceled without removing it from the upload list. If the file to be canceled is being uploaded, the system cancels the upload and automatically starts to upload the next file in the list.

    cancelFile(int index)
  • Resume a canceled file and automatically start to upload the file.

    resumeFile(int index)

Upload management

You can use the following methods to control the upload in the upload instance VODUploadClient:

  • Stop the upload. If a file is being uploaded, the system cancels the upload.

    void stop();
    Note

    If you need to resume the upload after you stop the upload, call the resumeFile method to resume the file to be uploaded. Alternatively, clear the upload list and add the file again to upload it.

  • Pause the upload.

    void pause();
  • Resume the upload.

    void resume();

Callback management

The following callbacks may be fired for the upload instance VODUploadClient:

  • onUploadFailed

    The onUploadFailed callback is fired when the upload fails. You can view the cause of the failure based on the code and message callback parameters. In addition, a prompt is displayed on the web page. For more information about error codes, see Error codes and Handle exceptions.

  • onUploadTokenExpired

    The onUploadTokenExpired callback is fired when the upload credential expires. You can send a request to the AppServer to obtain a new upload credential and call a method to resume the upload by using the new upload credential.

    Note

    You must specify the new upload credential in the callback.

  • uploadRetry

    When the upload times out, the uploadRetry callback is fired and the system automatically retries to upload the file. You can receive a prompt on the web page or call the cancel method to cancel the upload. In addition, you can set the maxRetryCount parameter to specify the maximum number of retries. If the retry result indicates that the upload can be resumed, the uploadRetryResume callback is fired and the upload is resumed.

Upload timeout

The upload instance VODUploadClient allows you to set the maximum number of retries when an upload times out.

/**
Set the timeout period and the maximum number of retries when an upload times out. The default value of the maximum number of retries is INT_MAX.
 */
void setVodHttpClientConfig(VodHttpClientConfig var);

Multipart upload

The upload instance VODUploadClient allows you to specify a file size as the threshold for multipart upload. If the size of a file to be uploaded exceeds the value specified for the partSize parameter, multipart upload is enabled.

/**
 Specify the size of each part in multipart upload. Default value: 1024 × 1024. Unit: bytes. If the size of a file to be uploaded exceeds the value specified for the partSize parameter, multipart upload is enabled. 
*/
void setPartSize(long partSize);

Storage address configuration

You can upload a file to a specific storage location by using the upload instance VODUploadClient. If the storage location is not specified, files are uploaded to the default storage location. If you need to upload files to a specific storage location, you must enable and configure the storage location in advance. For more information, see Overview.

/**
* Specify a storage location for the file. Log on to the ApsaraVideo VOD console. In the left-side navigation pane, choose Configuration Management > Media Management > Storage. On the Storage page, you can view the storage location. 
*/
void setStorageLocation(String storageLocation);

Transcoding

The upload instance VODUploadClient allows you to configure transcoding by specifying the ID of a transcoding template group.

/**
* Set the ID of the transcoding template group. Log on to the ApsaraVideo VOD console. In the left-side navigation pane, choose Configuration Management > Media Processing > Transcoding Template Groups. On the Transcoding Template Groups page, you can view the ID of the transcoding template group. 
*/
void setTemplateGroupId(String templateGroupId);
Important

If you use a client upload SDK to upload a file, you cannot configure transcoding by using workflows.

Resumable upload

The client upload SDKs support resumable upload. You need to only make sure that the value of the following method is YES.

/**
 * Specify whether to record the upload progress for a resumable upload. Default value: YES. The upload SDK automatically resumes an interrupted upload only when the parameter is set to YES. If you set the parameter to NO, the resumable upload feature is disabled. 
 */
void setRecordUploadProgressEnabled(boolean var1);

Region setting

The upload instance VODUploadClient allows you to set the region of the ApsaraVideo VOD service.

/**
 Specify the region of the ApsaraVideo VOD service. Default value: cn-shanghai. 
 */
void setRegion(String var);