All Products
Search
Document Center

Multipart upload

Last Updated: Jul 11, 2019

[TOC]

Procedure

  1. Request for the upload URL and credential or the STS credential. For more information, see relevant documentation.
  2. Initialize the upload instance by using either the upload URL and credential or the STS credential.
  3. Set callbacks for reporting the upload progress and all upload statuses, including upload success, upload failure, and credential expiration.
  4. Add files to the upload list. Currently, video and image files can be uploaded.
  5. Start the upload.
  6. Handle callbacks.

1. Request for the upload URL and credential or the STS credential

1.1 Request for the upload URL and credential

You need to call different API operations to obtain the upload URL and credential for image and video files. Video upload from the client: The client sends an upload request to the AppServer. The AppServer calls the CreateUploadVideo operation to send a request to ApsaraVideo for VOD to obtain the upload URL and credential. If the request succeeds, the AppServer receives the upload URL, upload credential, and VideoId, and returns them to the client. Image upload from the client: The client sends an upload request to the AppServer. The AppServer calls the CreateUploadImage operation to send a request to ApsaraVideo for VOD to obtain the upload URL and credential. If the request succeeds, the AppServer receives the upload URL, upload credential, and ImageURL, and returns them to the client.

1.2 Request for the STS credential

The client sends an upload request to the AppServer. The AppServer sends a request to STS to obtain a temporary credential. If the request succeeds, the AppServer receives the STS credential and returns it to the client.

2. Initialize the upload instance

First, declare an initialization callback VODUploadClient.

uploader = new VODUploadClientImpl(getApplicationContext());

2.1 Use the upload URL and credential

If you use the upload URL and credential to upload media files to ApsaraVideo for VOD, call the init method for initialization. You do not need to set the upload URL and credential obtained in the first step during initialization. Instead, set them in the SDK by calling the setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress) method in the onUploadStarted callback that is fired when the upload starts. When the credential expires, the onUploadTokenExpired callback is fired. You need to call the resumeWithAuth(uploadAuth) method to resume the upload with a new credential.

The sample code is as follows:

// Creates a VODUploadClient object.
final VODUploadClient uploader = new VODUploadClientImpl(getApplicationContext());

// Sets callbacks.
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 ------------- ");
                    // Calls the RefreshUploadVideo operation to update the upload credential.
                    uploadAuth = "The new 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 ------------- ");
                uploader.setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress);
            }
        };
// Initializes the upload instance.
uploader.init(callback);

2.2 Use STS

If you use STS to upload media files to ApsaraVideo for VOD, call the init(accessKeyId, accessKeySecret, secretToken, expireTime, callback) method for initialization.Use the temporary STS credential obtained in the first step as the initialization parameter. When the credential expires, the OnUploadTokenExpired callback is fired. You need to call the resumeWithToken(accessKeyId, accessKeySecret, secretToken, expireTime) method to resume the upload with a new STS credential.

// Creates a VODUploadClient object.
uploader = new VODUploadClientImpl(getApplicationContext());

//
// Sets callbacks.
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 ------------- ");
                    // Calls the resumeWithToken method after a new STS credential 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 ------------- ");
                uploader.setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress);
            }
        };
// Initializes the upload instance. Calls the resumeWithToken method to resume the upload with a new credential after the onUploadTokenExpired callback is fired upon credential expiration. By default, resumable upload is supported.
uploader.init(accessKeyId, accessKeySecret, secretToken, expireTime, callback);

3. Set callbacks

As shown in the preceding initialization code snippets, you need to set the VODUploadCallback object during initialization when you use either the upload URL and credential or the STS credential to upload media files. This object belongs to the class of callbacks for upload statuses. You need to set the following callbacks:

/**
 This callback is fired when the upload succeeds.

 @param info The information about the uploading file.
 @param result The upload result.
 */
 void onUploadFinished(UploadFileInfo info, VodUploadResult result);

/**
 This callback is fired when the upload fails.

 @param info The information about the uploading file.
 @param code The error code.
 @param message The error description.
 */
 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 uploading file.
 @param uploadedSize The size of uploaded parts.
 @param totalSize The total size of the uploading file.
 */
 void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize);

/**
 This callback is fired when the credential expires.
 If you use the upload URL and credential to upload media files, call the resumeWithAuth method to resume the upload upon credential expiration.
 If you use STS to upload media files, call the resumeWithToken method to resume the upload upon credential expiration.
 */
 void onUploadTokenExpired();

/**
 This callback is fired when the system retries the upload upon a network exception.
 */
 void onUploadRetry(String code, String message);

/**
 This callback is fired when the system recovers from the exception and resumes the upload.
 */
 void onUploadRetryResume ();

/**
 This callback is fired when the upload starts.
 If you use the upload URL and credential to upload media files, call the setUploadAuthAndAddress:uploadAuth:uploadAddress: method to set the upload URL and credential.
 @param fileInfo The information about the uploading file.
 */
  void onUploadStarted(UploadFileInfo uploadFileInfo);

4. Add files to the upload list

4.1 Add files

Add videos

String filePath = "The path of the video file";
VodInfo vodInfo = new VodInfo();
vodInfo.setTitle("The title" + index);
vodInfo.setDesc("The description" + index);
vodInfo.cateId (19);
vodInfo.tags("sports");
uploader.addFile(filePath,vodInfo);

Add images ``java String filePath = "The path of the image file"; VodInfo vodInfo = new VodInfo(); vodInfo.setTitle("The title" + index); vodInfo.setDesc("The description" + index); vodInfo.cateId (19); vodInfo.tags("sports"); uploader.addFile(filePath,vodInfo);

> Note: The size of the file to be uploaded cannot exceed 4 GB.

The structure of the VodInfo object is as follows:

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

After you add a file to be uploaded, the SDK encapsulates the file in the UploadFileInfo object with the following structure:
```java
// The local path of the file.
String filePath;
// The endpoint of OSS.
String endpoint;
// The bucket in OSS.
String bucket;
// The object in OSS.
String object;
// The file information returned by the SDK.
VodInfo vodInfo;

4.2 Manage the upload queue

VODUploadClient allows you to add multiple files to upload them in sequence. You can use the following methods to manage the upload queue. (1) Delete a file from the queue. If the file to be deleted is being uploaded, the system cancels uploading the file, and automatically starts uploading the next file in the queue.

void deleteFile(int index)

(2) Clear the upload queue. If the upload queue to be cleared contains a file that is being uploaded, the system cancels uploading the file.

void clearFiles()

(3) Obtain the upload queue.

List<UploadFileInfo> listFiles()

(4) Mark a file in the upload queue as canceled without deleting it from the upload queue. If the file to be canceled is being uploaded, the system cancels uploading the file, and automatically starts uploading the next file in the queue.

cancelFile(int index)

(5) Resume a canceled file and automatically start uploading the file.

resumeFile(int index)

The VODUploadClient object supports uploading multiple files. However, if you use the upload URL and credential to upload media files, you need to add the configuration for each file separately. Considering the code complexity of multi-file upload, we recommend that you add a single file to the VODUploadClient object.

5. Control the upload

Start the upload.

void start();

When this method is called, the onUploadStarted callback is fired. If you use the upload URL and credential to upload media files, set the upload URL and credential in this callback. The sample code is as follows:

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

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

void stop();

If you want to resume the upload after stopping it, call the resumeFile method to resume the file to be uploaded. Alternatively, clear the upload queue and add the file again to upload it.

Pause the upload.

void pause();

Resume the upload.

void resume();

6. Handle callbacks

6.1 Upload progress

The onUploadProgress callback is fired each time a part is uploaded. The callback parameters include uploadedSize (the size of uploaded parts) and totalSize (the total size of the uploading file).

6.2 Upload success

The onUploadSucceed callback is fired when the upload succeeds. The callback parameters include videoId or imageUrl.

After a video is uploaded, the videoId parameter is returned, indicating the video ID. Then, you need to obtain the playback URL to play the video. For more information, see Use playback URLs. After an image is uploaded, the imageUrl parameter is returned, indicating the image URL. The image URL will expire after a certain period of time if URL signing is enabled. For more information, see URL signing.

6.3 Upload failure

The onUploadFailed(String code, String message) callback is fired when the upload fails. You can view the cause of failure based on the callback parameters code and message. A prompt is displayed on the webpage accordingly. For more information about error codes, see ApsaraVideo for VOD error codes and OSS error codes.

6.4 Credential expiration

The onSTSTokenExpried callback is fired when the upload credential or STS credential expires. You can send a request to the AppServer to obtain a new upload credential or STS credential, and call the following method to resume the upload:

refreshSTSToken(accessKeyId,accessKeySecret,securityToken,expriedTime);

6.5 Upload timeout

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

Advanced settings

VODUploadClient supports the following advanced settings:

/**
 Specifies whether to transcode a file after it is uploaded to the ApsaraVideo for VOD server. The default value is Yes.
 */
void setTranscodeMode(boolean bool);

/**
 Specifies the size of each part in multipart upload. The default value is 1024 × 1024.
*/
void setPartSize(long partSize);

/**
* Specifies the storage region for video files.
*/
void setStorageLocation(String storageLocation);

/**
* Specifies the ID of the transcoding template group.
*/
void setTemplateGroupId(String templateGroupId);