Use the upload SDK for Android to upload media files from a local device to ApsaraVideo VOD.
Integrate the SDK
1. Install the Android SDK
Add the Android SDK dependency to your project’s app/build.gradle file.
dependencies {
implementation 'com.aliyun.video.android:upload:1.7.4'
}
Add the Alibaba Cloud Maven repository URL to the build.gradle file in the root directory.
allprojects {
repositories {
maven { url "https://maven.aliyun.com/nexus/content/repositories/releases" }
}
}
2. Install the OSS Android SDK
The upload SDK depends on the OSS SDK. Install the OSS Android SDK, then add the dependency to your Gradle project.
Basic configuration
2. Initialize the upload instance
Initialize the upload instance with either the upload URL and credential method or the STS token method.
Upload URL and credential method (recommended)
-
Declare the VODUploadClient initialization callback.
uploader = new VODUploadClientImpl(getApplicationContext());
-
Initialize VODUploadClient.
Note
-
Call init to initialize the upload instance.
-
In the onUploadStarted callback, call setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress) to set the upload URL and credential.
-
If the credential expires during upload, the onUploadTokenExpired callback fires. Call resumeWithAuth(uploadAuth) to resume with a new credential.
Expand to view 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 ------------- ");
// Refresh the upload credential by calling RefreshUploadVideo.
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 uploadAuth parameter is the upload credential. The uploadAddress parameter is the upload URL.
uploader.setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress);
}
};
// Initialize the upload instance.
uploader.init(callback);
STS token method
-
Declare the VODUploadClient initialization callback.
uploader = new VODUploadClientImpl(getApplicationContext());
-
Initialize VODUploadClient.
Note
-
Call init(accessKeyId, accessKeySecret, secretToken, expireTime, callback) to initialize the upload instance.
-
The secretToken parameter is the temporary STS token you obtained.
-
If the STS token expires, the onUploadTokenExpired callback fires. Call resumeWithToken(accessKeyId, accessKeySecret, secretToken, expireTime) to resume with a new token.
Show code
// create VODUploadClient object
uploader = new VODUploadClientImpl(getApplicationContext());
// 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 resumeWithToken after obtaining a new STS token.
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 fires. Call resumeWithToken to resume the upload with a new STS token. Resumable upload is enabled by default.
uploader.init(accessKeyId, accessKeySecret, secretToken, expireTime, callback);
3. Set the upload status callback class
Set VODUploadCallback to handle upload status callbacks:
Show code
/**
Callback fired when the upload succeeds.
@param info Information about the uploaded file.
*/
void onUploadSucceed(UploadFileInfo info);
/**
Callback fired when the upload fails.
@param info Information about the uploaded file.
@param code Error code.
@param message Error message.
*/
void onUploadFailed(UploadFileInfo info, String code, String message);
/**
Callback fired when the upload progress changes.
@param fileInfo Information about the uploaded file.
@param uploadedSize Size of uploaded parts.
@param totalSize Total size of the file.
*/
void onUploadProgress(UploadFileInfo fileInfo, long uploadedSize, long totalSize);
/**
Callback fired when the upload URL and credential expire.
If you use the upload URL and credential method, call resumeWithAuth to resume the upload.
If you use the STS token method, call resumeWithToken to resume the upload.
*/
void onUploadTokenExpired();
/**
Callback fired when the system retries the upload.
*/
void onUploadRetry(String code, String message);
/**
Callback fired when the system resumes the upload after a retry.
*/
void onUploadRetryResume ();
/**
Callback fired when the upload starts.
If you use the upload URL and credential method, call setUploadAuthAndAddress to specify the upload URL and credential.
@param fileInfo Information about the uploaded file.
*/
void onUploadStarted(UploadFileInfo fileInfo);
4. Construct the upload request function
Parameters for audio or video files
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
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 of vodInfo
// Title.
String title;
// Tags.
List tags;
// Description.
String desc;
// Category ID.
idInteger cateId;
// Thumbnail URL. Must be a complete URL that starts with https://.
String coverUrl;
Note
After you add a file to the upload list, the SDK wraps the file in an UploadFileInfo object. The structure of the object is as follows:
// Local path of the file.
String filePath;
// Endpoint.
String endpoint;
// Bucket.
String bucket;
// Object.
String object;
// VodInfo.
VodInfo vodInfo;
5. Start the upload
-
Call start() to begin the upload.
void start();
This triggers the onUploadStarted callback. If you use the upload URL and credential method, set the upload URL and credential in this callback:
void setUploadAuthAndAddress(UploadFileInfo uploadFileInfo, String uploadAuth, String uploadAddress)
-
The onUploadProgress callback reports upload progress.
-
On success, the onUploadSucceed callback returns the result, including videoId and imageUrl.
Execution result
6. Destroy
Call release() to free the upload instance and prevent memory and thread leaks.
void release();
Advanced features
Upload acceleration
VODUploadClient supports upload acceleration.
For large files (GB/TB) or cross-region uploads (for example, from the Chinese mainland to Singapore), enable upload acceleration, then add the UserData key-value pairs (as a JSON string) to vodInfo:
vodInfo.setUserData("{\"Type\":\"oss\",\"Domain\":\"oss-accelerate.aliyuncs.com\"}");
Parameters
|
Name
|
Type
|
Description
|
|
Type
|
string
|
Type of upload acceleration. Only OSS is supported.
|
|
Domain
|
string
|
Accelerated domain name of the bucket. Default value: https.
Note
An accelerated endpoint assigned after you enable upload acceleration, such as vod-*******.oss-accelerate.aliyuncs.com.
|
Queue management
VODUploadClient supports sequential multi-file uploads. Manage the queue with these methods:
Note
With upload URLs and credentials, each file requires separate configuration. Upload one file at a time for simplicity.
-
Remove a file from the queue. If in progress, the upload is canceled and the next file starts.
void deleteFile(int index)
-
Clear the upload queue. Any in-progress upload is canceled.
void clearFiles()
-
Retrieve the upload queue.
List<UploadFileInfo> listFiles()
-
Mark a file as canceled without removing it from the queue. If in progress, the upload is canceled and the next file starts.
cancelFile(int index)
-
Resume a canceled file. The upload starts automatically.
resumeFile(int index)
Upload control
VODUploadClient upload control methods:
Callback handling
VODUploadClient provides these callbacks:
-
Upload Failed
The onUploadFailed callback fires on failure. Check code and message to identify the cause. Error details: Error codes and OSS error codes.
-
Upload URL and Credentials Expiration
When the credential expires, onUploadTokenExpired fires. Request a new credential from your AppServer and call the appropriate resume method.
Note
Set the new credential inside this callback.
-
Upload timeout
On timeout, uploadRetry fires and the system retries automatically. Call cancel to stop, or set maxRetryCount to limit retries. On success, uploadRetryResume fires.
Timeout handling
VODUploadClient configures the maximum retry count for timeouts.
/**
Set the maximum number of retries for upload timeouts. Default value: INT_MAX.
*/
void setVodHttpClientConfig(VodHttpClientConfig var);
Multipart upload
VODUploadClient sets a file size threshold for multipart uploads. Files larger than partSize are uploaded in parts.
/**
Part size. Default value: 1024 × 1024. Unit: bytes. If a file exceeds the partSize value, multipart upload is used.
*/
void setPartSize(long partSize);
Storage location
VODUploadClient specifies a storage location. Files go to the default location if not specified. Enable and configure the storage location first. Overview.
/**
* Specify a storage location for the file. Log on to the ApsaraVideo VOD console. In the navigation pane on the left, choose Configuration Management > Media Management > Storage. On the Storage page, view the storage location.
*/
void setStorageLocation(String storageLocation);
Transcoding
VODUploadClient configures transcoding by specifying a template group ID.
/**
* Set the ID of the transcoding template group. Log on to the ApsaraVideo VOD console. In the navigation pane on the left, choose Configuration Management > Media Processing > Transcoding Template Groups. On the Transcoding Template Groups page, view the ID.
*/
void setTemplateGroupId(String templateGroupId);
VODUploadClient also supports a workflow ID.
/**
* Set the ID of the workflow. Log on to the ApsaraVideo VOD console. In the navigation pane on the left, choose Configuration Management > Media Processing > Workflow Management. On the Workflow Management page, view the ID.
*/
void setWorkflowId(String workflowId);
Important
If you set both a transcoding template group ID and a workflow ID, the workflow configuration takes precedence.
Resumable upload
The SDK supports resumable uploads. Set the following to true:
/**
* Enable recording of upload progress for resumable upload. Default value: true. The upload SDK automatically resumes interrupted uploads only when this parameter is set to true. If set to false, resumable upload is disabled.
*/
void setRecordUploadProgressEnabled(boolean var1);
Region setting
VODUploadClient sets the ApsaraVideo VOD service region.
/**
Specify the ApsaraVideo VOD service region. Default value: cn-shanghai.
*/
void setRegion(String var);