All Products
Search
Document Center

ApsaraVideo VOD:Upload using OSS SDK

Last Updated:Dec 09, 2025

Built on the OSS SDK, the Upload SDK simplifies the upload process. If the Upload SDK does not meet your needs or you require more flexible control, use the OSS SDK directly.

SDK support

The OSS SDK supports various programming languages, including Java, Python, Go, PHP, Node.js, and Ruby, as well as client platforms such as iOS, Android, and HarmonyOS. For more information, refer to Overview.

Workflow

Server-side upload

In a server-side upload scenario, your application server uses an OSS SDK (e.g., for Java, Python, or PHP) to upload a local file. Because the server is a secure environment, you can safely use your AccessKey pair. The workflow involves calling the ApsaraVideo VOD API from your server to obtain an upload URL and credential, and then using the OSS SDK to perform the upload.

image

Client-side upload

In a client-side upload scenario, the client (such as a web browser or mobile app) uses the OSS SDK to upload a file. To avoid exposing your AccessKey pair, you must set up an authorization service on your application server. The client first requests temporary upload URL and credential from your authorization service, and then uses them to upload the file to OSS.

image

Note:

  • For detailed steps and code examples on how the application server obtains the upload URL and credential from ApsaraVideo VOD, see Obtain an upload URL and credential.

  • The response includes the Base64-encoded upload URL (UploadAddress), upload credential (UploadAuth), and media asset ID. You must parse these parameters to use them as inputs for initializing the OSS SDK.

    Note
    • The UploadAddress field contains information about the target OSS bucket, while the UploadAuth field contains authorization information, including an STS token. You must Base64-decode both fields and use their contents to initialize the OSS SDK client. See Reference: Decode the upload URL and credential.

    • When providing the upload credentials, ApsaraVideo VOD also automatically creates a media asset entry and returns a media asset ID. You must save this media asset ID, as it is required for media management, playback, and processing tasks.

      • The VideoId is returned when you obtain an upload URL and credential for a video.

      • The ImageId is returned when you obtain an upload URL and credential for an image.

      • The MediaId is returned when you obtain an upload URL and credential for an auxiliary media asset.

Download demos

ApsaraVideo VOD provides demo source code for developers to reference:

Programmatic integration

The following section provides a detailed integration guide using Java as an example.

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 Obtain an STS token.

Environment requirements

  • Java 1.8 or later is required.

  • You can run the java -version command in the terminal to check the Java version.

Sample code

SDK V1.0

Step 1. Install dependencies

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.6.1</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-vod</artifactId>
  <version>2.16.32</version>
</dependency>
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.17.4</version>
</dependency>

Step 2. Upload the file

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;

/**
 * description
 */
public class UploadDemo {

    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // Specify the region where the ApsaraVideo VOD service is activated. For example, if the service is activated in the China (Shanghai) region, set the value to cn-shanghai. For more information about other regions, see Overview of media upload.
        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");
        // Example of CoverURL: http://example.aliyundoc.com/test_cover_****.jpg
        //request.setCoverURL("<your CoverURL>");
        //request.setCateId(-1L);
        //request.setTemplateGroupId("");
        //request.setWorkflowId("");
        //request.setStorageLocation("");
        //request.setAppId("app-1000000");
        // Set 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 APIs. We recommend that you use the AccessKey of a RAM user for API access or routine O&M.
        // Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
        // This example shows how to use an AccessKey pair that is obtained from environment variables to implement identity verification for API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
        // Your AccessKey ID.
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        // Your AccessKey secret.
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // The full path of the local video file that you want to upload to ApsaraVideo VOD. The path must include the file name extension.
        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 operation is successful, the 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 UploadAuth and UploadAddress to initialize the OSS client.
            OSSClient ossClient = initOssClient(uploadAuth, uploadAddress);
            // Upload the file. Note that the upload is synchronous and blocks the thread. The time consumed depends on the file size and the 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));
    }
}
                

SDK V2.0

Step 1. Install dependencies

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>vod20170321</artifactId>
      <version>3.6.4</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea-openapi</artifactId>
      <version>0.3.8</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea-console</artifactId>
      <version>0.0.1</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea-util</artifactId>
      <version>0.2.23</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>credentials-java</artifactId>
      <version>1.0.1</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.17.4</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.83</version>
    </dependency>

Step 2. Upload the file

Note

We recommend using a more secure credential configuration method that avoids hard-coding the AccessKey pair. For details, see Manage access credentials.

package com.aliyun.sample;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.tea.*;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import org.apache.commons.codec.binary.Base64;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Initialize the client using credentials.</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.vod20170321.Client createClient() throws Exception {
        com.aliyun.credentials.models.Config creditConfig = new com.aliyun.credentials.models.Config();
        creditConfig.setType("access_key")
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));

        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client(creditConfig);
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential);
        // The service endpoint. Refer to https://api.alibabacloud.com/product/vod.
        config.endpoint = "vod.cn-shanghai.aliyuncs.com";
        return new com.aliyun.vod20170321.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        
        com.aliyun.vod20170321.Client client = Sample.createClient();
        com.aliyun.vod20170321.models.CreateUploadVideoRequest createUploadVideoRequest = new com.aliyun.vod20170321.models.CreateUploadVideoRequest()
                .setFileName("ecs.mp4")
                .setTitle("ecs");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            com.aliyun.vod20170321.models.CreateUploadVideoResponse resp = client.createUploadVideoWithOptions(createUploadVideoRequest, runtime);
            // On success, the response contains VideoId, UploadAddress, and UploadAuth.
            String videoId = resp.getBody().videoId;
            String localFile = "/Users/yours/ecs.mp4";

            JSONObject uploadAuth = JSONObject.parseObject(decodeBase64(resp.getBody().uploadAuth));
            JSONObject uploadAddress = JSONObject.parseObject(decodeBase64(resp.getBody().uploadAddress));

            OSS ossClient = initOssClient(uploadAuth, uploadAddress);
            uploadLocalFile(ossClient, uploadAddress, localFile);

            System.out.println("Put local file succeed, VideoId : " + videoId);
        } catch (TeaException error) {
            // This is for demonstration only. In production, handle exceptions carefully and do not ignore them.
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // This is for demonstration only. In production, handle exceptions carefully and do not ignore them.
            // Error message.
            System.out.println(error.getMessage());
            // Diagnostic address.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }

    /**
     * Initialize OSS client.
     * @param uploadAuth
     * @param uploadAddress
     * @return
     */
    public static OSS 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");

        com.aliyun.credentials.models.Config creditConfig = new com.aliyun.credentials.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setSecurityToken(securityToken);

        DefaultCredentialProvider credentialsProvider = new CredentialsProviderFactory()
                .newDefaultCredentialProvider(accessKeyId, accessKeySecret, securityToken);


        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V1);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(endpoint)
                .build();

        return ossClient;
    }

    /**
     * Upload the local file
     * @param ossClient
     * @param uploadAddress
     * @param localFile
     * @throws Exception
     */
    public static void uploadLocalFile(OSS ossClient, JSONObject uploadAddress, String localFile) throws Exception {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
        File file = new File(localFile);
        PutObjectResult result = ossClient.putObject(bucketName, objectName, file);
        com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(result));
    }

    /**
     * Decode UploadAuth/UploadAddress
     * @param s
     * @return
     */
    public static String decodeBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            Base64 decoder = new Base64();
            try {
                b = decoder.decode(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
            }
        }
        return result;
    }
}

Reference: Decode the upload URL and credential

Base64-decode the UploadAddress and UploadAuth to get the OSS upload URL and authorization information. The decoded information can be used to initialize the OSS client. See the example code below:

  import org.apache.commons.codec.binary.Base64;
  
  
  public static String decodeBase64(String s) {
      byte[] b = null;
      String result = null;
      if (s != null) {
          Base64 decoder = new Base64();
          try {
              b = decoder.decode(s);
              result = new String(b, "utf-8");
          } catch (Exception e) {
          }
      }
      return result;
  }

Table 1. Decoded UploadAddress fields

Field

Description

Bucket

The storage bucket in ApsaraVideo VOD.

Endpoint

The ID of the storage region endpoint.

FileName

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

ObjectPrefix

Returned only when uploading an M3U8 file.

Table 2. Decoded UploadAuth fields

Field

Description

AccessKeyId

The AccessKey ID of the user who uploads the file.

AccessKeySecret

The AccessKey secret of the user who uploads the file.

SecurityToken

The security token for upload authorization.

ExpireUTCTime

The expiration time of the upload URL and credential. The time is in UTC and follows the yyyy-MM-ddTHH:mm:ssZ format.

Expiration

The validity period of the upload authorization in seconds. For videos, this is 3000 seconds. You must refresh the credential after it expires.

Region

The ID of the upload region.