All Products
Search
Document Center

ApsaraVideo VOD:Upload media files by using OSS SDKs

Last Updated:Sep 05, 2024

If the upload SDKs provided by ApsaraVideo VOD cannot meet your requirements for uploading files from application servers, you can upload media files by using Object Storage Service (OSS) SDKs. This topic describes the process of uploading media files by using OSS SDKs. This topic also describes the procedure and sample code of using OSS SDKs for specific programming languages.

Scenarios

ApsaraVideo VOD allows you to upload media files by using various methods. The server and client upload SDKs encapsulate fundamental upload logic. You only need to complete simple configurations before you can upload media files. We recommended that you use the upload SDKs to upload media files. However, the server upload SDKs support only the Java, Python, C, C++, and PHP programming languages. If you are using other programming languages such as .NET and Go, you can use OSS SDKs to upload media files. For more information about upload methods, see Overview.

The following table describes the supported and recommended upload methods for different programming languages.

Programming language

Supported upload method

Recommended upload method

Description

Java

Server upload SDK

OSS SDK

Note

This topic provides the sample code of uploading media files by using the OSS SDK.

Server upload SDK

For more information, see Upload from servers.

Python

Server upload SDK

OSS SDK

Server upload SDK

C/C++

Server upload SDK

OSS SDK

Server upload SDK

PHP

Server upload SDK

OSS SDK

Note

This topic provides the sample code of uploading media files by using the OSS SDK.

Server upload SDK

Go

OSS SDK

Note

This topic provides the sample code of uploading media files by using the OSS SDK.

-

You must integrate ApsaraVideo VOD SDK to obtain upload URLs and credentials.

This topic provides the sample code of uploading media files by using the OSS SDK.

.NET

OSS SDK

Note

This topic provides the sample code of uploading media files by using the OSS SDK.

-

Node.js

OSS SDK

-

You must integrate ApsaraVideo VOD SDK to obtain upload URLs and credentials.

This topic describes the procedure of uploading media files by using the OSS SDK. No sample code is provided.

Upload process

To upload media files by using OSS SDKs, you must implement the logic for the entire upload process. You need to obtain upload URLs and credentials from ApsaraVideo VOD, decode the Base64-encoded upload URLs and credentials, and then use OSS SDKs to upload media files.

The following figure shows the complete upload process. In this example, ApsaraVideo VOD SDK is integrated to obtain upload URLs and credentials.

上传流程

Process description

  1. An application server uses the AccessKey ID and AccessKey secret of a RAM user or a temporary AccessKey pair issued by Security Token Service (STS) to initialize an ApsaraVideo VOD client.

  2. The application server calls one of the following operations by using ApsaraVideo VOD SDK to obtain an upload URL, an upload credential, and media asset information.

    Note

    You can also construct an HTTP or HTTPS request to obtain the upload URL and credential. However, you must manually sign the request, which has a high error probability. For more information about the API operations related to upload URLs and credentials, see the following topics:

  3. ApsaraVideo VOD returns the Base64-encoded upload URL in the UploadAddress parameter, the Base64-encoded upload credential in the UploadAuth parameter, and information such as the media ID. The application server decodes the returned parameters and uses the decoded information as input parameters to initialize the OSS SDK.

    Note

    For more information about decoded upload URLs and credentials, see Notes for decoding upload URLs and credentials.

    ApsaraVideo VOD generates media IDs when it issues upload URLs and credentials. Media IDs can be used for lifecycle management and media processing.

    • ApsaraVideo VOD returns the media ID for a video file in the VideoId parameter.

    • ApsaraVideo VOD returns the media ID for an image file in the ImageId parameter.

    • ApsaraVideo VOD returns the media ID for an auxiliary media asset 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.

  4. The application server uses the decoded upload URL (UploadAddress) and upload credential (UploadAuth) to initialize an OSS client with an STS token.

    Important

    To prevent the leakage of your AccessKey pair, you must use STS tokens to initialize OSS SDKs.

  5. The application server calls an operation by using the OSS SDK to upload media files to the specified storage address.

  6. OSS returns the upload result.

    Note

    You can also set callbacks for the upload-related events to receive the upload result.

Prerequisites

  • ApsaraVideo VOD is activated. For more information, see Activate ApsaraVideo VOD.

  • The system settings required for the upload, including the storage path in the specified region and the callback settings, are configured. For more information, see Manage storage buckets and Configure callbacks.

  • A RAM user is created and used to access ApsaraVideo VOD. To prevent security risks caused by the leakage of the AccessKey pair of your Alibaba Cloud account, we recommend that you create a RAM user and grant the RAM user the permissions required to access ApsaraVideo VOD. Then, you can use the AccessKey pair of the RAM user to access ApsaraVideo VOD. For more information, see Create and grant permissions to a RAM user.

  • Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.

    Important
    • The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use the AccessKey pair of a RAM user to call API operations or perform routine O&M.

    • We recommend that you do not hard-code the AccessKey ID and AccessKey secret into your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account is compromised.

  • Optional. A role is created for the RAM user and the role is granted the permissions required to access ApsaraVideo VOD if you want to access ApsaraVideo VOD by using Security Token Service (STS). For more information, see Use STS to upload videos.

    Note

    For more information about the scenarios in which STS can be used, see Comparison between credentials and STS.

Procedure

Important

Replace the values of parameters in the sample code with the actual values based on your business requirements. For more information about the API operations related to upload URLs and credentials, see the following topics:

In the sample code, video files are uploaded. The CreateUploadVideo operation is called to obtain upload URLs and credentials.

Source code of the demo

The source code of the upload demo is provided for your reference. The following table provides the links to the source code of the upload demo in different programming languages.

Language

Source code

References

PHP

Source code of the upload demo for PHP

OSS SDK for PHP

Go

Source code of the upload demo for Go

OSS SDK for Go

.NET

Source code of the upload demo for .NET

OSS SDK for .NET

Java

Source code of the upload demo for Java

OSS SDK for Java

Procedure and sample code of using OSS SDK for PHP

Step 1: Install the ApsaraVideo VOD SDK

For more information, see Quick Start.

Step 2: Install the OSS SDK

Important

Prepare the environment by performing the following operations:

  • Install PHP 5.3 or later. To check the PHP version, run the php -v command on the CLI.

  • Install the cURL extension. To check whether the curl extension is installed, run the php -m command on the CLI.

  1. Download the latest source code package of OSS SDK for PHP from the aliyun-oss-php-sdk page.

  2. Decompress the package and copy the decompressed folder to the aliyun-php-sdk folder.

    For example, if aliyun-oss-php-sdk-2.4.3.zip is downloaded and decompressed, the decompressed folder is aliyun-oss-php-sdk-2.4.3. For more information, see Installation.

Step 3: Upload media files

Note

Troubleshooting methods

  • If an error such as "cURL error: SSL certificate problem" occurs due to improper SSL configurations, replace https with http before you initialize an OSS client.

    $uploadAddress['Endpoint'] = str_replace("https:", "http:", $uploadAddress['Endpoint']);
  • If the upload credential expires, you must update the upload credential and upload the media file again. By default, an upload credential is valid for 3,000 seconds. The following sample code provides an example on how to update an upload credential:

    function refresh_upload_video($vodClient, $videoId) {
        $request = new vod\RefreshUploadVideoRequest();
        $request->setVideoId($videoId);
        return $vodClient->getAcsResponse($request);
    }
<?php
// 1. Reference the files of ApsaraVideo VOD and OSS in the code. 
  // In this example, your source code file is in the aliyun-php-sdk folder. 
require_once './aliyun-php-sdk/aliyun-php-sdk-core/Config.php';   
require_once './aliyun-php-sdk/aliyun-oss-php-sdk-2.4.3/autoload.php';
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;
// 2. Initialize an ApsaraVideo VOD client by using an AccessKey pair. 
function init_vod_client($accessKeyId, $accessKeySecret) {
  // Specify the region in which ApsaraVideo VOD is activated. Example: cn-shanghai.
    $regionId = 'cn-shanghai';     
    $profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
    return new DefaultAcsClient($profile);
}
// 3. Obtain an upload URL and an upload credential.
function create_upload_video($vodClient) {
    $request = new vod\CreateUploadVideoRequest();
    $request->setTitle("Video title");        // Required. The title of the video.
    $request->setFileName("File name.mov"); // Required. The name of the source video file, which must contain a file name extension.
    $request->setDescription("Video description");  // Optional. The description of the source video file.
  // CoverURL example: http://example.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-****.png.
    $request->setCoverURL("<URL of the video thumbnail>"); // Optional. The URL of the custom video thumbnail.
    $request->setTags("Tag 1,Tag 2"); // Optional. The tags of the video. Separate multiple video tags with commas (,).
    return $vodClient->getAcsResponse($request);
}

// 4. Use the upload URL and credential to initialize an OSS client with an STS token. 
function init_oss_client($uploadAuth, $uploadAddress) {
    $ossClient = new OssClient($uploadAuth['AccessKeyId'], $uploadAuth['AccessKeySecret'], $uploadAddress['Endpoint'],
        false, $uploadAuth['SecurityToken']);
  // The request timeout period. Unit: seconds. Default value: 5184000. We recommend that you set the parameter to a large value because the upload of large files takes a long time.
    $ossClient->setTimeout(86400*7);  
  // The connection timeout period. Unit: seconds. Default value: 10.
    $ossClient->setConnectTimeout(10);  
    return $ossClient;
}
// 5. Upload a video file. 
function upload_local_file($ossClient, $uploadAddress, $localFile) {
    return $ossClient->uploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
// We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'); // Your AccessKey ID.
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'); // Your AccessKey secret.
$localFile = '/Users/aligame/Downloads/****.mp4';   // The full path of the local video file to be uploaded to ApsaraVideo VOD.
try {
    // Initialize the ApsaraVideo VOD client and obtain the upload URL and credential.
    $vodClient = init_vod_client($accessKeyId, $accessKeySecret);
    $createRes = create_upload_video($vodClient);
    // If the execution is successful, VideoId, UploadAddress, and UploadAuth are returned. Decode the Base64-encoded upload URL and upload credential. 
    $videoId = $createRes->VideoId;
    $uploadAddress = json_decode(base64_decode($createRes->UploadAddress), true);
    $uploadAuth = json_decode(base64_decode($createRes->UploadAuth), true);
    // Use the obtained upload URL and upload credential to initialize an OSS client.
    $ossClient = init_oss_client($uploadAuth, $uploadAddress);
    // Upload a video file. Take note that multiple parts are uploaded in parallel. The system starts to upload the next file only when all parts of the current file have been uploaded. The consumed time depends on the file size and upstream bandwidth.
    $result = upload_local_file($ossClient, $uploadAddress, $localFile);
    printf("Succeed, VideoId: %s", $videoId);
} catch (Exception $e) {
    // var_dump($e);
    printf("Failed, ErrorMessage: %s", $e->getMessage());
}
                

Procedure and sample code of using OSS SDK for Go

Step 1: Install the ApsaraVideo VOD SDK

For more information, see Quick Start.

Step 2: Install the OSS SDK

Important

Prepare the environment by performing the following operations:

Install Go 1.7 or later. You can visit the official website of Go to download an appropriate version.

  1. Run the go get or glide command to install Alibaba Cloud SDK for Go.

    • Run the go get command to install Alibaba Cloud SDK for Go.

      go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk
      Note
      • No messages appear during the installation. The installation process requires a few minutes to complete. If the installation times out, run the command again.

      • If the src/github.com/aliyun/alibaba-cloud-sdk-go/services/vod subfolder appears in the folder that is specified by the GOPATH variable, the SDK is installed.

    • Run the glide command to install Alibaba Cloud SDK for Go.

      glide get github.com/aliyun/alibaba-cloud-sdk-go
  2. Install the OSS SDK. For more information, see Installation.

Step 3: Upload media files

 package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
    "github.com/aliyun/alibaba-cloud-sdk-go/services/vod"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

func InitVodClient(accessKeyId string, accessKeySecret string) (client *vod.Client, err error) {
    // Specify the storage region of ApsaraVideo VOD.
    regionId := "cn-shanghai"
    // Create an object for authorization.
    credential := &credentials.AccessKeyCredential{
        accessKeyId,
        accessKeySecret,
    }
    // The custom configuration parameters.
    config := sdk.NewConfig()
    config.AutoRetry = true     // Specifies whether to automatically reconnect to the network if a connection fails.
    config.MaxRetryTime = 3     // The maximum number of retry attempts.
    config.Timeout = 3000000000 // The connection timeout period. Unit: nanoseconds. Default value: 3000000000.
    // Create a vodClient instance.
    return vod.NewClientWithOptions(regionId, config, credential)
}

func MyCreateUploadVideo(client *vod.Client) (response *vod.CreateUploadVideoResponse, err error) {
    request := vod.CreateCreateUploadVideoRequest()
    request.Title = "Sample Video Title"
    request.Description = "Sample Description"
    request.FileName = "/opt/video/sample/video_file.mp4"
    //request.CateId = "-1"
    // Sample URL of the video thumbnail: example:http://example.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-****.png.
    request.CoverURL = "<your CoverURL>"
    request.Tags = "tag1,tag2"
    request.AcceptFormat = "JSON"
    return client.CreateUploadVideo(request)
}

func InitOssClient(uploadAuthDTO UploadAuthDTO, uploadAddressDTO UploadAddressDTO) (*oss.Client, error) {
    client, err := oss.New(uploadAddressDTO.Endpoint,
        uploadAuthDTO.AccessKeyId,
        uploadAuthDTO.AccessKeySecret,
        oss.SecurityToken(uploadAuthDTO.SecurityToken),
        oss.Timeout(86400*7, 86400*7))
    return client, err
}

func UploadLocalFile(client *oss.Client, uploadAddressDTO UploadAddressDTO, localFile string) {
    // Obtain a storage location. 
    bucket, err := client.Bucket(uploadAddressDTO.Bucket)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Upload the local file. 
    err = bucket.PutObjectFromFile(uploadAddressDTO.FileName, localFile)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}

type UploadAuthDTO struct {
    AccessKeyId     string
    AccessKeySecret string
    SecurityToken   string
}
type UploadAddressDTO struct {
    Endpoint string
    Bucket   string
    FileName string
}

func main() {
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
    // We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
    // In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
    var accessKeyId string=os.Getenv ('ALIBABA_CLOUD_ACCESS_KEY_ID'); // Your AccessKey ID.
    var accessKeySecret string=os.Getenv ('ALIBABA_CLOUD_ACCESS_KEY_SECRET); // Your AccessKey secret.
    var localFile string = "/opt/video/sample/video_file.mp4"     // The full path of the local video file to be uploaded to ApsaraVideo VOD.
    // Initialize the ApsaraVideo VOD client and obtain the upload URL and credential.
    var vodClient, initVodClientErr = InitVodClient(accessKeyId, accessKeySecret)
    if initVodClientErr != nil {
        fmt.Println("Error:", initVodClientErr)
        return
    }
    // Obtain an upload URL and an upload credential.
    var response, createUploadVideoErr = MyCreateUploadVideo(vodClient)
    if createUploadVideoErr != nil {
        fmt.Println("Error:", createUploadVideoErr)
        return
    }
    // If the execution is successful, VideoId, UploadAddress, and UploadAuth are returned.
    var videoId = response.VideoId
    var uploadAuthDTO UploadAuthDTO
    var uploadAddressDTO UploadAddressDTO
    var uploadAuthDecode, _ = base64.StdEncoding.DecodeString(response.UploadAuth)
    var uploadAddressDecode, _ = base64.StdEncoding.DecodeString(response.UploadAddress)
    json.Unmarshal(uploadAuthDecode, &uploadAuthDTO)
    json.Unmarshal(uploadAddressDecode, &uploadAddressDTO)
    // Use the obtained upload URL and upload credential to initialize an OSS client.
    var ossClient, _ = InitOssClient(uploadAuthDTO, uploadAddressDTO)
    // Upload a video file. Take note that multiple parts are uploaded in parallel. The system starts to upload the next file only when all parts of the current file have been uploaded. The consumed time depends on the file size and upstream bandwidth.
    UploadLocalFile(ossClient, uploadAddressDTO, localFile)
    //MultipartUploadFile(ossClient, uploadAddressDTO, localFile)
    fmt.Println("Succeed, VideoId:", videoId)
}
                

Procedure and sample code of using OSS SDK for Java

Important

Prepare the environment by performing the following operations:

  • Install Java 1.8 or later.

  • To check the Java version, run the java -version command on the CLI.

Step 1: Install the ApsaraVideo VOD SDK

For more information, see Quick Start.

Step 2: Install OSS SDK for Java

For more information, see Installation.

Step 3. Upload media files

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import org.apache.commons.codec.binary.Base64;

import java.io.File;

/**
 * descript
 */
public class UploadDemo {

    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // Specify the region in which ApsaraVideo VOD is activated. Example: cn-shanghai. For more information about other regions, see Overview. 
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    public static CreateUploadVideoResponse createUploadVideo(DefaultAcsClient vodClient) throws ClientException {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setFileName("vod_test.mp4");
        request.setTitle("this is title");
        //request.setDescription("this is desc");
        //request.setTags("tag1,tag2");
        // Sample URL of the video thumbnail: http://example.aliyundoc.com/test_cover_****.jpg.
        //request.setCoverURL("<your CoverURL>");
        //request.setCateId(-1L);
        //request.setTemplateGroupId("");
        //request.setWorkflowId("");
        //request.setStorageLocation("");
        //request.setAppId("app-1000000");
        // The request timeout period.
        request.setSysReadTimeout(1000);
        request.setSysConnectTimeout(1000);
        return vodClient.getAcsResponse(request);
    }

    public static OSSClient initOssClient(JSONObject uploadAuth, JSONObject uploadAddress) {
        String endpoint = uploadAddress.getString("Endpoint");
        String accessKeyId = uploadAuth.getString("AccessKeyId");
        String accessKeySecret = uploadAuth.getString("AccessKeySecret");
        String securityToken = uploadAuth.getString("SecurityToken");
        return new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    }

    public static void uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, String localFile) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
        File file = new File(localFile);
        ossClient.putObject(bucketName, objectName, file);
    }

    public static void main(String[] argv) {
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
        // We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
        // In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
        // Specify your AccessKey ID.
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        // Specify your AccessKey secret.
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Specify the full path of the local file that you want to upload to ApsaraVideo VOD. The file name extension must be included in the path.
        String localFile = "/Users/yours/Video/testVideo.flv";
        try {
            // Initialize the ApsaraVideo VOD client and obtain the upload URL and credential.
            DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
            CreateUploadVideoResponse createUploadVideoResponse = createUploadVideo(vodClient);
            // If the execution is successful, VideoId, UploadAddress, and UploadAuth are returned.
            String videoId = createUploadVideoResponse.getVideoId();

            JSONObject uploadAuth = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAuth()));
            JSONObject uploadAddress = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAddress()));

            // Use the obtained upload URL and upload credential to initialize an OSS client.
            OSSClient ossClient = initOssClient(uploadAuth, uploadAddress);
            // Upload a video file. Take note that multiple parts are uploaded in parallel. The system starts to upload the next file only when all parts of the current file have been uploaded. The consumed time depends on the file size and upstream bandwidth.
            uploadLocalFile(ossClient, uploadAddress, localFile);
            System.out.println("Put local file succeed, VideoId : " + videoId);
        } catch (Exception e) {
            System.out.println("Put local file fail, ErrorMessage : " + e.getLocalizedMessage());
        }
    }

    private static String decodeBase64(String data) {
        return new String(Base64.decodeBase64(data));
    }
}
                

Procedure and sample code of using OSS SDK for .NET

Important

Prepare the environment by performing the following operations:

  • Install .NET Framework 4.6.1 or later.

  • Install .NET Standard 2.0 or later.

Step 1: Install the ApsaraVideo VOD SDK

For more information, see Quick Start.

Step 2: Install the OSS SDK

For more information, see Installation.

Step 3: Initialize an ApsaraVideo VOD client

public static DefaultAcsClient InitVodClient(string accessKeyId, string accessKeySecret)
{
    // Specify the region in which ApsaraVideo VOD is activated. Example: cn-shanghai.
    string regionId = "cn-shanghai";
    IClientProfile profile = DefaultProfile.GetProfile(regionId, accessKeyId, accessKeySecret);
    return new DefaultAcsClient(profile);
}

Step 4: Upload media files

  1. Obtain an upload URL and an upload credential. In this example, a video file is uploaded.

    public static CreateUploadVideoResponse CreateUploadVideo(DefaultAcsClient vodClient)
    {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.AcceptFormat = Aliyun.Acs.Core.Http.FormatType.JSON;
        request.FileName = "vod_test.mp4";
        request.Title = "this is title";
        // request.Description = "<File description>";
        // request.Tags = "<Tags of the video. Separate multiple video tags with commas (,).>";
        // Sample URL of the video thumbnail: http://example.aliyundoc.com/test_cover_****.jpg.
        // request.CoverURL = "<The video thumbnail URL>";
        // The category ID. Log on to the ApsaraVideo VOD console to query the category ID.
        //request.CateId = -1;
        // The ID of the transcoding template group. Log on to the ApsaraVideo VOD console to query the ID of the transcoding template group.
        // request.TemplateGroupId = "<Transcoding template group ID>";
        // The ID of the workflow. Log on to the ApsaraVideo VOD console to query the ID of the workflow.
        // request.WorkflowId = "<Workflow ID>";
        // The storage address of the video file. Log on to the ApsaraVideo VOD console to query the storage address.
        // request.StorageLocation = "<Storage address>";
        // The value of the AppId parameter is fixed. 
        //request.AppId = "app-1000000";
        // The request timeout period.
        request.SetReadTimeoutInMilliSeconds(1000);
        request.SetConnectTimeoutInMilliSeconds(1000);
        return vodClient.GetAcsResponse(request);
    }
  2. Decode the Base64-encoded upload URL and upload credential.

  3. Use the upload URL and upload credential to initialize an OSS client.

    Important
    • Before you use the upload URL and upload credential, decode them in the Base64 format and then in the JSON format.

    • You must use an STS token to initialize the OSS client.

    Examples

    public static OssClient InitOssClient(JObject uploadAuth, JObject uploadAddress) 
    {
        string endpoint = uploadAddress.GetValue("Endpoint").ToString();
        string accessKeyId = uploadAuth.GetValue("AccessKeyId").ToString();
        string accessKeySecret = uploadAuth.GetValue("AccessKeySecret").ToString();
        string securityToken = uploadAuth.GetValue("SecurityToken").ToString();
        return new OssClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    }
  4. Upload a local file.

    Examples

    public static void UploadLocalFile(OssClient ossClient, JObject uploadAddress, string localFile) 
    {
        string bucketName = uploadAddress.GetValue("Bucket").ToString();
        string objectName = uploadAddress.GetValue("FileName").ToString();
        ossClient.PutObject(bucketName, objectName, localFile);
    }
  5. (Optional) If the upload credential expires, update the upload credential and upload the media file again.

    Examples

    public static RefreshUploadVideoResponse RefreshUploadVideo(DefaultAcsClient vodClient)
    {
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        request.AcceptFormat = Aliyun.Acs.Core.Http.FormatType.JSON;
        request.VideoId = "VideoId";
        // The request timeout period.
        request.SetReadTimeoutInMilliSeconds(1000);
        request.SetConnectTimeoutInMilliSeconds(1000);
        return vodClient.GetAcsResponse(request);
    }
  6. Run the whole upload process. Capture exceptions during the execution.

    Examples

    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
    // We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
    // In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
    // Specify your AccessKey ID.
    String accessKeyId = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
    // Specify your AccessKey secret.
    String accessKeySecret = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    // Specify the full path of the local file that you want to upload to ApsaraVideo VOD. The file name extension must be included in the path.
    string localFile = "/Users/yours/Video/testVideo.flv";
    try {
        // Initialize the ApsaraVideo VOD client and obtain the upload URL and credential.
        DefaultAcsClient vodClient = InitVodClient(accessKeyId, accessKeySecret);
        CreateUploadVideoResponse createUploadVideoResponse = CreateUploadVideo(vodClient);
        // If the execution is successful, VideoId, UploadAddress, and UploadAuth are returned.
        String videoId = createUploadVideoResponse.VideoId;
        JObject uploadAuth = JObject.Parse(Base64Decode(createUploadVideoResponse.UploadAuth));
        JObject uploadAddress = JObject.Parse(Base64Decode(createUploadVideoResponse.UploadAddress));
        // Use the obtained upload URL and upload credential to initialize an OSS client.
        OssClient ossClient = InitOssClient(uploadAuth, uploadAddress);
        // Upload a video file. Take note that multiple parts are uploaded in parallel. The system starts to upload the next file only when all parts of the current file have been uploaded. The consumed time depends on the file size and upstream bandwidth.
        UploadLocalFile(ossClient, uploadAddress, localFile);
        Console.WriteLine("Put local file succeed, VideoId : " + videoId);
    } 
    catch (Exception e) 
    {
        Console.WriteLine("Put local file fail, ErrorMessage : " + e.Message);
    }

References for other programming languages

If the upload SDKs and sample code for the preceding programming languages cannot meet your business requirements, check the following table for references for more programming languages.

Note

For more information about the upload SDKs provided by ApsaraVideo VOD, see the related topics. To learn how to upload media files by using OSS SDKs for PHP, Java, Go, and .NET, see the sample code in this topic.

Programming language

ApsaraVideo VOD SDK

OSS SDK

Node.js

  1. For more information about how to install and initialize ApsaraVideo VOD SDK for Node.js, see Quick Start.

  2. To obtain the upload URL and credential, use the upload logic of ApsaraVideo VOD SDK in other languages as references and visit Alibaba Cloud OpenAPI Explorer to perform online debugging and generate SDK examples. For more information, see Automatically generate SDK sample code

  1. Installation

  2. Initialization

  3. Upload objects

Notes for decoding upload URLs and credentials

You can decode the values of the UploadAddress and UploadAuth parameters returned by ApsaraVideo VOD by using the Base64 algorithm to obtain upload URLs and credentials. You can use the decoded upload URLs and credentials to initialize OSS clients.

Note

Base64 decoding is a common task for developers. Therefore, no specific tools are described in this topic. This section describes the fields decoded from the uploadAddress and uploadAuth parameters.

Table 1. Fields decoded from the UploadAddress parameter

Field

Describe

Bucket

The storage location of ApsaraVideo VOD.

Endpoint

The endpoint of the ApsaraVideo VOD storage region.

FileName

The name assigned by ApsaraVideo VOD to the media file to be uploaded.

ObjectPrefix

The field that is returned only for an M3U8 file.

Table 2. Fields decoded from the UploadAuth parameter

Field

Describe

AccessKeyId

The AccessKey ID of the account that is used to upload the media file.

AccessKeySecret

The AccessKey secret of the account that is used to upload the media file.

SecurityToken

The security token for upload authorization.

ExpireUTCTime

The time when the upload URL and upload credential expire. The time follows the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. The time is displayed in UTC.

Expiration

The expiration time of the upload credential. The validity period of an upload credential is 3,000 seconds. You must update the upload credential after it expires.

Region

The ID of the storage region.

The following code shows the sample upload URLs and credentials before and after decoding.

Sample UploadAddress and UploadAuth parameters before decoding

{
"VideoId": "1c1255e7e58d4d7487d0c1852954****",
"UploadAddress": "eyJFbmRwb2ludCI6Imh0dHBzOi8vb3NzLWNuLXNoYW5naGFpLmFsaXl1bmNzLmNvbSIsIkJ1Y2tldCI6InZvZC1zaGFuZ2hhaS1rYXNpIiwiRmlsZU5hbWUiOiJ2b2QtZjFlOGM0L3N2LzFhYmUyZDVjLTE3ZWU3Zjc3ZjA0LzFhYmUyZDVjLTE3ZWU3Zjc3ZjA0Lm1w****",
"RequestId": "2975D91A-F89F-5EBF-97D5-07028C90****",
"UploadAuth": "eyJTZWN1cml0eVRva2VuIjoiQ0FJUzhRUjFxNkZ0NUIyeWZTaklyNWZNQ3Z6NWg1aFEzWVc2VVhmVDEwNFpXUGtVaHE3Z3B6ejJJSGhFZjNWdEErOGN0LzQxbFdsVzUvWWFscklxRk1NVkhSMlVNWkFvdjgwT3ExLzdKb0hidk5ldTBic0hoWnY5OEtzbG9waThqcUhvZU96Y1lJNzN2cHpQQWdtMldFUVJySkwrY1RLOUpaZlBVL21nZ29KbWFkSTZSeFN4YVNFOGF2NWRPZ3BscnIzNFh4bTBNdTIyWUNiM25rM2FEa2RqcG1nYWpuaGt1NXk0MmRHNzRCalRoMEdZc3VnT3ZOYllPb0NwYWNWTE5wVnlXTXZYdXV0dGJmamgzU2RjekJKSStheHE3dFZENGl5VmtkeUJKRk5UN2g2YUZ1ZkkrNzhjS3hSaU5JazhHckpGcGVUeHNPQjhwdTNMbnA3cjlnNUpPdWhaTVYvWVg1dnk1ZGJBQk9LeFA4d2xTSzcvUEgzQnNMYUlMWUtuamhzZ1puc1hEQXBRWjdoYkxXUnJXeUUwVGpiVEpwZXU0a3poWlIreUtkdUN5N3BrK3AxdzExSGw0ZGV2T2x5VFFxMlF5em9sSXBzN1prOUtSeGtOeGo3SWVLZ2NieWxSZDA5bUg3K1BVYmhyYUJkWHBjR1l1aGJKQkFsaDFXMXlvdm5pWnV2Zm9Md2ljWUg0VjU1ZHMrOGFmNDhVbDJveFUyeitVYTYxOEZoMkVsWm9XckZMeXFMZ0ZJYWk0YnVldW9XcGJQWEJGK29NdHlkcEV3SFlwREhmVG1oTGYyK2pwSTg5YmxiZDRNVFl5cVBNK3BJbEV3STE1NWRCQ2czQWY0OWcvMWM2cExDc3FFMmErdUs1WGkyaHV6Tm45OVNIOGRZUTV4TTRPYTZ0aWVMSXNtUFYrU1hQYktSbWxwaUlWalV6QnhHdkoxNEJtYS9PMWlwVzkweGF5ekR0WWt4RHNXNzhqempnSUpjcHRkV1EzVzVCRDZ0cG51RFZkaXl0NUcwSUM2alN1K1pRQmI0NEk3b1hDS3p0aEY4NGxxWDkwelMwdXB6Y3R5bENTOEw1ZWJJN1o1SnlCQmIrOEJzNXppV3FXRGtKR29BQmg1Z3M3YlVOZEs2NGdVaThRM2tOdWpVZFdiZTFTb1Y1cVZJOEdmTkYvZ1g0MUNvWGlrSHhwN3FwOTBpMFBSd1h5VUc4WEVkVGUxY3RZbGEwZG9WeGhtNThOQVdoR0pEOXQxK21iWjd4ZUFkczNqT3NpSUNPb25Ib3JWYmNUb0s2VGs3cjNxejZHSlgybE54djVmWTBvUWZsSTJNQWR0cHo5WnJidnZ5eUFjYz0iLCJBY2Nlc3NLZXlJZCI6IlNUUy5OVHlBRk1qR3FqR1FTUWIzTkxUdjhpa0tFIiwiRXhwaXJlVVRDVGltZSI6IjIwMjItMDItMTFUMDk6NTc6NDNaIiwiQWNjZXNzS2V5U2VjcmV0IjoiOWZGUXQyeVJSWTZGMVBFb0hNS1dMYmFmeHlSd1BNNjFuRUhDbzZDTWlQZCIsIkV4cGlyYXRpb24iOiIzNjAwIiwiUmVnaW9uIjoiY24tc2hhbmdoYWk****"
}

Sample UploadAddress parameter after decoding

{
"Endpoint": "https://******.aliyuncs.com",
"Bucket": "vod-shanghai-****",
"FileName": "vod-f1e8c4/sv/1abe2d5c-17ee7f77f04/1abe2d5c-17ee7f7****.mp4"
}
Important

If an M3U8 file is uploaded, the ObjectPrefix field is decoded from the UploadAddress parameter. Example:

Sample UploadAddress parameter after decoding for an M3U8 file

{
"Endpoint": "https://******.aliyuncs.com",
"Bucket": "vod-shanghai-****",
"ObjectPrefix": "vod-f1e8c4/sv/4b9c68b2-17ee8156****",
"FileName": "vod-f1e8c4/sv/4b9c68b2-17ee81564e7/4b9c68b2-17ee815****.m3u8"
}

Sample UploadAuth parameter after decoding

{
"SecurityToken": "CAIS8QR1q6Ft5B2yfSjIr5fMCvz5h5hQ3YW6UXfT104ZWPkUhq7gpzz2IHhEf3VtA+8ct/41lWlW5/YalrIqFMMVHR2UMZAov80Oq1/7JoHbvNeu0bsHhZv98Kslopi8jqHoeOzcYI73vpzPAgm2WEQRrJL+cTK9JZfPU/mggoJmadI6RxSxaSE8av5dOgplrr34Xxm0Mu22YCb3nk3aDkdjpmgajnhku5y42dG74BjTh0GYsugOvNbYOoCpacVLNpVyWMvXuuttbfjh3SdczBJI+axq7tVD4iyVkdyBJFNT7h6aFufI+78cKxRiNIk8GrJFpeTxsOB8pu3Lnp7r9g5JOuhZMV/YX5vy5dbABOKxP8wlSK7/PH3BsLaILYKnjhsgZnsXDApQZ7hbLWRrWyE0TjbTJpeu4kzhZR+yKduCy7pk+p1w11Hl4devOlyTQq2QyzolIps7Zk9KRxkNxj7IeKgcbylRd09mH7+PUbhraBdXpcGYuhbJBAlh1W1yovniZuvfoLwicYH4V55ds+8af48Ul2oxU2z+Ua618Fh2ElZoWrFLyqLgFIai4bueuoWpbPXBF+oMtydpEwHYpDHfTmhLf2+jpI89blbd4MTYyqPM+pIlEwI155dBCg3Af49g/1c6pLCsqE2a+uK5Xi2huzNn99SH8dYQ5xM4Oa6tieLIsmPV+SXPbKRmlpiIVjUzBxGvJ14Bma/O1ipW90xayzDtYkxDsW78jzjgIJcptdWQ3W5BD6tpnuDVdiyt5G0IC6jSu+ZQBb44I7oXCKzthF84lqX90zS0upzctylCS8L5ebI7Z5JyBBb+8Bs5ziWqWDkJGoABh5gs7bUNdK64gUi8Q3kNujUdWbe1SoV5qVI8GfNF/gX41CoXikHxp7qp90i0PRwXyUG8XEdTe1ctYla0doVxhm58NAWhGJD9t1+mbZ7xeAds3jOsiICOonHorVbcToK6Tk7r3qz6GJX2lNxv5fY0oQflI2MAdtpz9Zrbvvy****",
"AccessKeyId": "STS.NTyAFMjGqjGQSQb3NLTv8****",
"ExpireUTCTime": "2022-02-11T******",
"AccessKeySecret": "9fFQt2yRRY6F1PEoHMKWLbafxyRwPM61nEHCo6C****",
"Expiration": "****",
"Region": "cn-shanghai"
}