To upload a file is to upload a media file from a client 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 client. 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 a file
Perform the following steps to upload a file from an Android client:
Obtain an upload URL and an upload credential or a Security Token Service (STS) token.
Initialize the upload instance by using the obtained upload credential or STS token.
Set callbacks to receive key messages during the upload.
Construct upload parameters based on the type of the file to be uploaded. You can upload audio, a video, or an image.
Start the upload.
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.
For more information about how to deploy the authorization service and obtain an upload URL and an upload credential, see Use upload URLs and credentials to upload media files.
For more information about how to deploy STS and obtain an STS token, see Obtain an STS token.
Execution result
The obtained upload URL and credential or STS token are used as an input parameter 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.
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
.
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 theonUploadStarted
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 theresumeWithAuth(uploadAuth)
method to resume the upload by using a new upload credential.
// create VODUploadClient
final VODUploadClient 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 the RefreshUploadVideo operation to update the upload credential.
uploadAuth = "The new upload credential";
uploader.resumeWithAuth(uploadAuth);
}
public void onUploadRetry(String code, String message) {
OSSLog.logError("onUploadRetry ------------- ");
}
public void onUploadRetryResume() {
OSSLog.logError("onUploadRetryResume ------------- ");
}
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);
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
.
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 theresumeWithToken(accessKeyId, accessKeySecret, secretToken, expireTime)
method to resume the upload by using a new STS token.
// 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:
/**
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 info, 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 uploadFileInfo);
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.
javaString 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;
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;
// The OSS endpoint.
String endpoint;
//The OSS bucket.
String bucket;
// The OSS object.
String object;
//VodInfo
VodInfo vodInfo;
Step 5: Start the upload
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. The following sample code provides an example:void setUploadAuthAndAddress(UploadFileInfo uploadFileInfo, String uploadAuth, String uploadAddress)
After the file starts to be uploaded, the
onUploadProgress
callback is fired to synchronize the upload progress.After the file is uploaded, the
onUploadSucceed
callback is fired to return the upload result. The callback parameters includevideoId
andimageUrl
.
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 authentication.
Manage the upload list
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:
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)
Control the upload
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();
NoteIf 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();
Handle callbacks
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 thecode
andmessage
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.
You must specify the new upload credential in the callback.
onSTSTokenExpired
The onSTSTokenExpried
callback is fired when the STS token expires. You can send a request to the AppServer to obtain a new STS token and call the following method to resume the upload:
refreshSTSToken(accessKeyId,accessKeySecret,securityToken,expriedTime);
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 thecancel
method to cancel the upload. In addition, you can set themaxRetryCount
parameter to specify the maximum number of retries. If the retry result indicates that the upload can be resumed, theuploadRetryResume
callback is fired and the upload is resumed.
Advanced features
Timeout processing
The upload instance VODUploadClient
allows you to set the maximum number of retries when an upload times out.
/**
Set the maximum number of retries when an upload times out. The default value is INT_MAX, which means that the maximum number of retries equals the timeout period.
*/
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);
Upload to a specific storage location
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);
Configure transcoding
The upload instance VODUploadClient
allows you to configure transcoding by specifying the ID of a transcoding template group.
/**
* Specify the ID of a 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);
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);
Set the region of the ApsaraVideo VOD service
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);