Upload media files using OSS SDKs

更新时间:
复制 MD 格式

The Upload SDK wraps the OSS SDK to simplify uploads. Use the OSS SDK directly when you need finer control over the upload process.

SDK support

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

Workflow

Server-side upload

Your application server uses an OSS SDK (Java, Python, PHP, etc.) to upload files. Since the server is a trusted environment, you can use your AccessKey pair directly. The server calls the ApsaraVideo VOD API to obtain an upload URL and credential, then uploads through the OSS SDK.

image

Client-side upload

The client (web browser or mobile app) uploads files through the OSS SDK. To keep your AccessKey pair secure, set up an authorization service on your application server. The client requests a temporary upload URL and credential from this service, then uploads directly 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), credential (UploadAuth), and media asset ID. Decode and parse these values to initialize the OSS SDK.

    Note
    • The UploadAddress field contains the target OSS bucket info, and the UploadAuth field contains authorization details including an STS token. Base64-decode both fields to initialize the OSS SDK client. See Reference: Decode the upload URL and credential.

    • ApsaraVideo VOD automatically creates a media asset entry and returns a media asset ID with the upload credentials. Save this ID — it is required for media management, playback, and processing.

      • 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

Demo source code:

Programmatic integration

The following Java example shows the full integration.

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 a RAM user and grant permissions.

  • 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
    • An Alibaba Cloud account AccessKey pair has permissions on all API operations. Use a RAM user's AccessKey pair to call API operations or perform routine O&M.

    • Do not hard-code your AccessKey ID and AccessKey secret in project code. If leaked, all resources in your account are 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 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 UploadAddress and UploadAuth to obtain the OSS endpoint and authorization details for initializing the OSS client:

  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 VOD storage bucket.

Endpoint

The storage region endpoint.

FileName

The file name VOD assigns to the uploaded file.

ObjectPrefix

Returned only when uploading an M3U8 file.

Table 2. Decoded UploadAuth fields

Field

Description

AccessKeyId

Temporary AccessKey ID for the upload.

AccessKeySecret

Temporary AccessKey secret for the upload.

SecurityToken

STS security token for the upload.

ExpireUTCTime

Expiration time of the credential in UTC (yyyy-MM-ddTHH:mm:ssZ).

Expiration

Validity period in seconds. For videos, this is 3000 seconds. Refresh the credential after expiration.

Region

The upload region ID.