All Products
Search
Document Center

ApsaraVideo VOD:Upload a file

Last Updated:Dec 26, 2023

You can upload a media file to ApsaraVideo VOD. The media file can be a local file or an online file. On iOS devices, the upload instance VODUploadClient is used to upload files. This topic describes how to use the upload SDK for iOS to upload a file.

Prerequisites

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

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

To upload a file on iOS, perform the following steps:

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

    Two authorization methods are provided for the upload SDK for iOS. We recommend that you use an upload credential for authorization.

    Result

    Use the obtained upload URL and credential or the obtained STS token to initialize the upload instance.

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

    You need to configure the initialization callback before you initialize the upload instance.

    1. Declare the VODUploadClient instance, which cannot be a local variable.

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

      • (Recommended) Initialize the upload instance by using the upload URL and credential

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

        • You do not need to specify the obtained upload URL and credential during initialization. Instead, specify them in the SDK by calling the setUploadAuthAndAddress: uploadAuth:uploadAddress: method in the OnUploadStartedListener callback that is fired when the upload starts.

        • If the upload credential expires, the OnUploadTokenExpiredListener callback is fired. To resume the upload by using a new upload credential, call the resumeWithAuth method.

        Show code

        // Create a VODUploadClient object.
        self.uploader = [VODUploadClient new];
        //weakself
        __weak typeof(self) weakSelf = self;
        //setup callback
        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.");
            // Specify 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.");
            // Specify 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;
        //init with upload address and upload auth
        [self.uploader init:listener];
      • Initialize the upload instance by using the STS token

        Note
        • If you use the STS token, call the init method to initialize the upload instance and the setKeyId:accessKeySecret:secretToken:expireTime:listener: method to specify the STS token.

        • When the STS token expires, the OnUploadTokenExpiredListener callback is fired. To resume the upload by using a new STS token, call the resumeWithToken: accessKeySecret: secretToken: expireTime method.

        Show code

        // Create a VODUploadClient object.
        self.uploader = [VODUploadClient new];
        //weakself
        __weak typeof(self) weakSelf = self;
        //setup callback
        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.");
            // Specify a new STS token to resume the upload upon token 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.");
        };
        //init
        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;
        //set STS and listener
        [self.uploader setKeyId:`STS Key Id` accessKeySecret:`STS Key Secret` secretToken:STS Secret Token` expireTime:`STS Expire Time` listener:listener];
  3. Configure callbacks to receive key messages during the upload.

    Set the VODUploadListener object, which belongs to the class of callbacks for upload statuses. You must set the following callbacks:

    Show code

    /**
     The callback that is fired when the upload succeeds.
     @param fileInfo The information about the file that you upload.
     @param result The upload result.
     */
    typedef void (^OnUploadFinishedListener) (UploadFileInfo* fileInfo, VodUploadResult* result);
    /**
     The callback that is fired when the upload fails.
     @param fileInfo The information about the file that you upload.
     @param code The error code.
     @param message The error message.
     */
    typedef void (^OnUploadFailedListener) (UploadFileInfo* fileInfo, NSString *code, NSString * message);
    /**
     The callback that 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.
     */
    typedef void (^OnUploadProgressListener) (UploadFileInfo* fileInfo, long uploadedSize, long totalSize);
    /**
     The callback that is fired when the STS token expires.
     If you use the upload URL and credential to upload a file, call the resumeWithAuth: method to resume the upload.
     If you use the STS token to upload a file, call the resumeWithToken:accessKeySecret:secretToken:expireTime: method to resume the upload.
     */
    typedef void (^OnUploadTokenExpiredListener) ();
    /**
     The callback that is fired when the system retries the upload.
     */
    typedef void (^OnUploadRertyListener) ();
    /**
     The callback that is fired when the system resumes the upload after the upload retry is complete.
     */
    typedef void (^OnUploadRertyResumeListener) ();
    /**
     The callback that 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.
     */
    typedef void (^OnUploadStartedListener) (UploadFileInfo* fileInfo);
  4. Construct upload parameters based on the type of the file to be uploaded. You can upload audio, video, or image files.

    Note

    The upload parameters for images are slightly different from those for audio and video files. You cannot upload auxiliary media assets by using client upload SDKs.

    Upload parameters for audio and video files

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

    Show code

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"The name of the source video." ofType:@"The format of the source video. Example: mp4."];
    VodInfo *vodInfo = [[VodInfo alloc] init];
    vodInfo.title = @"The name of the uploaded video.";
    vodInfo.desc =@"The description of the uploaded video.";
    vodInfo.ca teId = @(The category ID of the uploaded video.);
    vodInfo.tags = @"The video tags, such as sports.";
    [self.uploader addFile:filePath vodInfo:vodInfo];

    Structure of the VodInfo object

    Show code

    // 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 that starts with https://.
    @property (nonatomic, copy) NSString* coverUrl;

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

    Show code

    // The local path of the file.
    @property (nonatomic, copy) NSString* filePath;
    //endpoint
    @property (nonatomic, copy) NSString* endpoint;
    //bucket
    @property (nonatomic, copy) NSString* bucket;
    //object
    @property (nonatomic, copy) NSString* object;
    //VodInfo
    @property (nonatomic, strong) VodInfo* vodInfo;
    Note

    If you want to upload a video from an album, set the filePath parameter to the absolute path of the video that is selected by using the selector.

    Upload parameters for image files

    Show code

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"The name of the source image." ofType:@"The format of the source image. Example: jpg."];
    VodInfo *imageInfo = [[VodInfo alloc] init];
    vodInfo.title = @"The name of the uploaded image.";
    vodInfo.desc =@"The description of the uploaded image.";
    vodInfo.ca teId = @(The category ID of the uploaded image.);
    vodInfo.tags = @"The image tags, such as sports.";
    [self.uploader addFile:filePath vodInfo:imageInfo];
  5. Start the upload.

    1. The start method is called to start the upload.

      [self.uploader start];

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

      [weakSelf.uploader setUploadAuthAndAddress:fileInfo uploadAuth:weakSelf.uploadAuth uploadAddress:weakSelf.uploadAddress];
    2. When the upload starts, the OnUploadProgressListener callback is fired to synchronize the upload progress.

      The callback parameters include uploadedSize and totalSize. The uploadedSize parameter indicates the size of the uploaded parts, and the totalSize parameter indicates the total size of the file that you upload.

    3. After the file is uploaded, the OnUploadFinishedListener callback is returned. In the callback message, the UploadFileInfo parameter indicates the file information and the VodUploadResult parameter indicates the upload result.

      The VodUploadResult object contains the following properties:

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

      A value is returned for the videoId parameter only if a video is uploaded by using the STS token. A value is returned for the imageUrl parameter only if an image is uploaded by using the STS token. If you use the upload URL and credential to upload a file, the videoId and imageUrl parameters are not returned. You can obtain the values of the parameters when you obtain the upload URL and credential.

Result

  • After a video is uploaded, the videoId parameter is returned. The value of the videoId parameter indicates the video ID. Then, you can obtain the streaming URL to play the video. For more information, see Obtain playback URLs 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.

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.

    - (BOOL)deleteFile:(int) index;
  • Clear the upload list. If the upload list to be cleared contains a file that is being uploaded, the system cancels the upload.

    - (BOOL)clearFiles;
  • Query the upload list.

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

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

    - (BOOL)resumeFile:(int)index;

Upload management

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

    - (BOOL)stop;
    Note

    If you want 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.

    - (BOOL)pause;
  • Resume the upload.

    - (BOOL)resume;

Handle callbacks

  • Upload failure

    The OnUploadFailedListener callback is invoked if 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.

  • Credential or token expiration

    The OnUploadTokenExpiredListener callback is invoked if the upload credential or STS token expires. You can send a request to the AppServer to obtain a new upload credential or STS token, and call the following method to resume the upload:

    • Specify a new upload credential

      - (BOOL)resumeWithAuth:(NSString *)uploadAuth;
    • Specify a new STS token

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

    If the upload times out, the OnUploadRertyListener callback is invoked and the system automatically retries to upload the file. You can receive a prompt on the web page or call the stop method to stop 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 OnUploadRertyResumeListener callback is invoked and the upload is resumed.

Advanced settings

The VODUploadClient instance supports the following advanced settings: transcoding, retries upon a timeout, cache path, resumable upload, multipart upload, and service region. Sample code:

Transcoding

/**
 Specify whether to transcode a video when it is uploaded to ApsaraVideo VOD. Default value: YES. For more information about video transcoding formats, see Audio and video transcoding. 
 */
@property (nonatomic, assign) BOOL transcode;

Retries upon a timeout

/**
 Specify the maximum number of retries allowed upon a timeout. Default value: INT_MAX.
 */
@property (nonatomic, assign) uint32_t maxRetryCount;
/**
 Specify the timeout period.
 */
@property (nonatomic, assign) NSTimeInterval timeoutIntervalForRequest;

Cache path

/**
 Specify the path in which cached data is stored.
 */
@property (nonatomic, copy) NSString * recordDirectoryPath;

Resumable upload

/**
 Specify whether to record the upload progress for a resumable upload. Default value: YES.
 */
@property (nonatomic, assign) BOOL recordUploadProgress;

Multipart upload

/**
 Specify the size of each part in multipart upload. Default value: 1024 × 1024.
*/
@property (nonatomic, assign) NSInteger uploadPartSize;

Service region

/**
 Specify the region in which ApsaraVideo VOD is activated. Default value: cn-shanghai.
 */
@property (nonatomic, copy) NSString *region;