All Products
Search
Document Center

Multipart upload

Last Updated: Jul 11, 2019

Overview

The file upload object VODUploadClient allows you to upload media files to ApsaraVideo for VOD by using the upload URL and credential or the STS credential. We recommend that you use the upload URL and credential.

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 a VODUploadClient object. It must not be a local variable.

@property (nonatomic, strong) VODUploadClient *uploader;

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: uploadAuth:uploadAddress: method in the OnUploadStartedListener callback that is fired when the upload starts.

When the credential expires, the OnUploadTokenExpiredListener callback is fired. You need to call the resumeWithAuth: method to resume the upload with a new credential.

// Creates a VODUploadClient object.
self.uploader = [VODUploadClient new];
// Creates a weak reference to self.
__weak typeof(self) weakSelf = self;
// Sets callbacks.
OnUploadFinishedListener FinishCallbackFunc = ^(UploadFileInfo* fileInfo, VodUploadResult* result){
    NSLog(@"upload finished callback videoid:%@, imageurl:%@", result.videoId, result.imageUrl);
};
OnUploadFailedListener FailedCallbackFunc = ^(UploadFileInfo* fileInfo, NSString *code, NSString* message){
    NSLog(@"upload failed callback code = %@, error message = %@", code, message);
};
OnUploadProgressListener ProgressCallbackFunc = ^(UploadFileInfo* fileInfo, long uploadedSize, long totalSize) {
    NSLog(@"upload progress callback uploadedSize : %li, totalSize : %li", uploadedSize, totalSize);
};
OnUploadTokenExpiredListener TokenExpiredCallbackFunc = ^{
    NSLog(@"upload token expired callback.");
    // Sets a new upload credential to resume the upload upon credential expiration.
    [weakSelf.uploader resumeWithAuth:`new upload auth`];
};
OnUploadRertyListener RetryCallbackFunc = ^{
    NSLog(@"upload retry begin callback.") ;
};
OnUploadRertyResumeListener RetryResumeCallbackFunc = ^{
    NSLog(@"upload retry end callback.") ;
};
OnUploadStartedListener UploadStartedCallbackFunc = ^(UploadFileInfo* fileInfo) {
    NSLog(@"upload upload started callback.") ;
    // Sets the upload URL and credential.
    [weakSelf.uploader setUploadAuthAndAddress:fileInfo uploadAuth:`upload auth` uploadAddress:`upload address`];
};

VODUploadListener *listener = [[VODUploadListener alloc] init];
listener.finish = FinishCallbackFunc;
listener.failure = FailedCallbackFunc;
listener.progress = ProgressCallbackFunc;
listener.expire = TokenExpiredCallbackFunc;
listener.retry = RetryCallbackFunc;
listener.retryResume = RetryResumeCallbackFunc;
listener.started = UploadStartedCallbackFunc;
// Initializes the upload instance with the upload URL and credential.
[self.uploader init:listener];

2.2 Use STS

If you use STS to upload media files to ApsaraVideo for VOD, call the init: accessKeySecret: secretToken: expireTime: listener: method for initialization. Use the temporary STS credential obtained in the first step as the initialization parameter.

When the credential expires, the OnUploadTokenExpiredListener callback is fired. You need to call the resumeWithToken: accessKeySecret: secretToken: expireTime: method to resume the upload with a new STS credential.

// Creates a VODUploadClient object.
self.uploader = [VODUploadClient new];
// Creates a weak reference to self.
__weak typeof(self) weakSelf = self;
// Sets callbacks.
OnUploadFinishedListener FinishCallbackFunc = ^(UploadFileInfo* fileInfo,  VodUploadResult* result){ 
    NSLog(@"upload finished callback videoid:%@, imageurl:%@", result.videoId, result.imageUrl);
};
OnUploadFailedListener FailedCallbackFunc = ^(UploadFileInfo* fileInfo, NSString *code, NSString* message){
    NSLog(@"upload failed callback code = %@, error message = %@", code, message);
};
OnUploadProgressListener ProgressCallbackFunc = ^(UploadFileInfo* fileInfo, long uploadedSize, long totalSize) {
    NSLog(@"upload progress callback uploadedSize : %li, totalSize : %li", uploadedSize, totalSize);
};
OnUploadTokenExpiredListener TokenExpiredCallbackFunc = ^{
    NSLog(@"upload token expired callback.");
    // Sets a new STS credential to resume the upload upon credential expiration.
    [weakSelf.uploader resumeWithToken:`STS Key Id` accessKeySecret:`STS Key Secret` secretToken:`STS Secret Token` expireTime:`STS Expire Time`];
};
OnUploadRertyListener RetryCallbackFunc = ^{
    NSLog(@"upload retry begin callback.") ;
};
OnUploadRertyResumeListener RetryResumeCallbackFunc = ^{
    NSLog(@"upload retry end callback.") ;
};
OnUploadStartedListener UploadStartedCallbackFunc = ^(UploadFileInfo* fileInfo) {
    NSLog(@"upload upload started callback.");
};
// Initializes the upload instance.
VODUploadListener *listener = [[VODUploadListener alloc] init];
listener.finish = FinishCallbackFunc;
listener.failure = FailedCallbackFunc;
listener.progress = ProgressCallbackFunc;
listener.expire = TokenExpiredCallbackFunc;
listener.retry = RetryCallbackFunc;
listener.retryResume = RetryResumeCallbackFunc;
listener.started = UploadStartedCallbackFunc;
// Initializes the upload instance with the STS credential.
[self.uploader init:`STS Key Id` accessKeySecret:`STS Key Secret` secretToken:STS Secret Token` expireTime:`STS Expire Time` listener:listener];

3. Set callbacks

As shown in the preceding initialization code snippets, you need to set the VODUploadListener 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 fileInfo The information about the uploading file.
 @param result The upload result.
 */
typedef void (^OnUploadFinishedListener) (UploadFileInfo* fileInfo, VodUploadResult* result);

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

 @param fileInfo The information about the uploading file.
 @param code The error code.
 @param message The error description.
 */
typedef void (^OnUploadFailedListener) (UploadFileInfo* fileInfo, NSString *code, NSString * 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.
 */
typedef void (^OnUploadProgressListener) (UploadFileInfo* fileInfo, 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:accessKeySecret:secretToken:expireTime: method to resume the upload upon credential expiration.
 */
typedef void (^OnUploadTokenExpiredListener) ();

/**
 This callback is fired when the system retries the upload upon a network exception.
 */
typedef void (^OnUploadRertyListener) ();

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

/**
 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.
 */
typedef void (^OnUploadStartedListener) (UploadFileInfo* fileInfo);

4. Add files to the upload list

4.1 Add files

Add videos

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp4"];
VodInfo *vodInfo = [[VodInfo alloc] init];
vodInfo.title = @"title";
vodInfo.desc =@"desc";
vodInfo.cateId = @(19);
vodInfo.tags = @"sports";
[self.uploader addFile:filePath vodInfo:vodInfo];

Add images

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
VodInfo *imageInfo = [[VodInfo alloc] init];
imageInfo.title = @"title";
imageInfo.desc =@"desc";
imageInfo.cateId = @(19);
imageInfo.tags = @"sports";
[self.uploader addFile:filePath vodInfo:imageInfo];

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

The structure of the VodInfo object is as follows:

// The title.
@property (nonatomic, copy) NSString* title;
// The tags.
@property (nonatomic, copy) NSString* tags;
// The description.
@property (nonatomic, copy) NSString* desc;
// The category ID.
@property (nonatomic, strong) NSNumber* cateId;
// The URL of the thumbnail. The value must be a complete URL starting with https://.
@property (nonatomic, copy) NSString* coverUrl;

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

// The local path of the file.
@property (nonatomic, copy) NSString* filePath;
// The endpoint of OSS.
@property (nonatomic, copy) NSString* endpoint;
// The bucket in OSS.
@property (nonatomic, copy) NSString* bucket;
// The object in OSS.
@property (nonatomic, copy) NSString* object;
// The file information returned by the SDK.
@property (nonatomic, strong) 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.

- (BOOL)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.

- (BOOL)clearFiles;

(3) Obtain the upload queue.

- (NSMutableArray<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.

- (BOOL)cancelFile:(int)index;

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

- (BOOL)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.

[self.uploader start];

When this method is called, the OnUploadStartedListener 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:

[weakSelf.uploader setUploadAuthAndAddress:fileInfo uploadAuth:weakSelf.uploadAuth uploadAddress:weakSelf.uploadAddress];

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

- (BOOL)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.

- (BOOL)pause;

Resume the upload.

- (BOOL)resume;

6. Handle callbacks

6.1 Upload progress

The OnUploadProgressListener 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 OnUploadFinishedListener callback is fired when the upload succeeds. The callback parameters include UploadFileInfo (the information about the uploading file) and VodUploadResult (the upload result). The VodUploadResult parameter contains the following parameters:

@property (nonatomic, copy) NSString* videoId;
@property (nonatomic, copy) NSString* imageUrl;

Note: The videoId or imageUrl parameter is returned only when a video or an image is uploaded to ApsaraVideo for VOD through STS. If you use the upload URL and credential to upload a video or an image, the videoId or imageUrl parameter is not returned. You can obtain the parameter value when you request for the upload URL and credential.

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 OnUploadFailedListener 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 OnUploadTokenExpiredListener 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:

Set a new upload credential

- (BOOL)resumeWithAuth:(NSString *)uploadAuth;

Set a new STS credential

- (BOOL)resumeWithToken:(NSString *)accessKeyId
        accessKeySecret:(NSString *)accessKeySecret
            secretToken:(NSString *)secretToken
             expireTime:(NSString *)expireTime;

6.5 Upload timeout

When the upload times out, the OnUploadRertyListener callback is fired and the system automatically retries to upload files. You can receive a prompt on the webpage or call the stop 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 OnUploadRertyResumeListener 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.
 */
@property (nonatomic, assign) BOOL transcode;

/**
 Specifies the maximum number of retry times upon a timeout. The default value is INT_MAX.
 */
@property (nonatomic, assign) uint32_t maxRetryCount;

/**
 Specifies the timeout period.
 */
@property (nonatomic, assign) NSTimeInterval timeoutIntervalForRequest;

/**
 Specifies the path of the cache directory.
 */
@property (nonatomic, copy) NSString * recordDirectoryPath;

/**
 Specifies whether to record the upload progress for resumable upload. The default value is Yes.
 */
@property (nonatomic, assign) BOOL recordUploadProgress;

/**
 Specifies the size of each part in multipart upload. The default value is 1024 × 1024.
*/
@property (nonatomic, assign) NSInteger uploadPartSize;

/**
 Specifies the storage region in ApsaraVideo for VOD. The default value is cn-shanghai.
 */
@property (nonatomic, copy) NSString *region;