All Products
Search
Document Center

Upload videos by using the OSS native SDK

Last Updated: Aug 13, 2019

Scenarios

ApsaraVideo for VOD supports various video upload methods, including client upload and server upload. However, it may not provide upload SDKs of your required language, such as Go. In this case, you can upload videos through the OSS native SDK.

Prerequisites

Before getting started with this topic, make sure that ApsaraVideo for VOD does not provide the upload SDK of your required language. ApsaraVideo for VOD supports the following SDKs:

You can also go to the SDK download page to download the required SDK and demo. If ApsaraVideo for VOD does not provide the upload SDK of your required language, you can continue with this topic for development.

Preparations

Procedure

Upload process.png

1. Log on to the ApsaraVideo for VOD console and obtain the upload URL and credential.

A media asset record and the video ID are created in this step. Keep the video ID properly for future video playback, management, and AI processing.

2. Decode the upload URL (UploadAddress) and upload credential (UploadAuth) to obtain the OSS upload URL and authentication information. For more information about the decoding method, see Decode the upload URL and credential.

3. Call the OSS SDK to upload the video file to the specified bucket by using STS authentication. Use the decoded upload URL and authentication information, rather than your AccessKey, for initialization.

Code implementation

  • Perform the following steps to implement the core code:

    1. Use the AccessKey to initialize the ApsaraVideo for VOD client.
    2. Obtain the video upload URL and credential.
    3. Use the upload credential and URL to initialize the OSS client.
    4. Upload a local file.
  • You can use the API or SDK of ApsaraVideo for VOD to obtain the upload URL and credential.

  • You can use the OSS SDKs of the following languages to upload videos on the server:

PHP upload example

Environment requirements

  • Ensure that you have installed PHP 5.3 or later. You can run the php -v command to view the current PHP version.
  • Ensure that you have installed cURL extension. You can run the php -m command to check whether cURL extension is installed.

Installation

  1. Add the empty folder aliyun-php-sdk to your PHP project.

  2. Download the entire source code from aliyun-openapi-php-sdk. Decompress the downloaded package and copy the aliyun-php-sdk-core and aliyun-php-sdk-vod folders to the aliyun-php-sdk directory.

  3. Download the latest source code of OSS PHP SDK from aliyun-oss-php-sdk, decompress the ZIP file, and then copy the generated folder to the aliyun-php-sdk directory. For example, if v. 2.2.4 Source code (zip) is downloaded and decompressed, the generated folder is aliyun-oss-php-sdk-2.2.4.

  4. Open the aliyun-php-sdk/aliyun-php-sdk-core/Config.php file, locate “//config sdk auto load path.”, and add the following code below this line:

  1. Autoloader::addAutoloadPath("aliyun-php-sdk-vod");
  1. Reference the ApsaraVideo for VOD and OSS files in the code:
  1. require_once './aliyun-php-sdk/aliyun-php-sdk-core/Config.php'; // Assume that your source code file is in the same directory as aliyun-php-sdk.
  2. require_once './aliyun-php-sdk/aliyun-oss-php-sdk-2.2.4/autoload.php';
  3. use vod\Request\V20170321 as vod;
  4. use OSS\OssClient;
  5. use OSS\Core\OssException;

For more information, see ApsaraVideo for VOD PHP SDK installation and OSS PHP SDK installation.

Reference code

  • Define the methods of the core steps:

1. Use the AccessKey to initialize the ApsaraVideo for VOD client.

  1. function init_vod_client($accessKeyId, $accessKeySecret) {
  2. $regionId = 'cn-shanghai'; // The region of ApsaraVideo for VOD. Enter cn-shanghai for a region in China.
  3. $profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
  4. return new DefaultAcsClient($profile);
  5. }

2. Obtain the video upload URL and credential.

  1. function create_upload_video($vodClient) {
  2. $request = new vod\CreateUploadVideoRequest();
  3. $request->setTitle("Video title"); // (Required) The video title.
  4. $request->setFileName("File name.mov"); // (Required) The name of the video mezzanine file, which must contain an extension.
  5. $request->setDescription("Video description"); // (Optional) The description of the video mezzanine file.
  6. $request->setCoverURL("http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png"); // (Optional) The custom video thumbnail.
  7. $request->setTags("Tag 1,tag 2"); // (Optional) The video tags. Separate multiple video tags with commas (,).
  8. return $vodClient->getAcsResponse($request);
  9. }

3. Use the upload credential and URL to initialize the OSS client. Perform Base-64 decoding and JSON decoding before initialization.

  1. function init_oss_client($uploadAuth, $uploadAddress) {
  2. $ossClient = new OssClient($uploadAuth['AccessKeyId'], $uploadAuth['AccessKeySecret'], $uploadAddress['Endpoint'],
  3. false, $uploadAuth['SecurityToken']);
  4. $ossClient->setTimeout(86400*7); // Set the request timeout period, in seconds. The default value is 5184000. We recommend that you set the parameter to a large value because it takes a long time to upload a large file.
  5. $ossClient->setConnectTimeout(10); // Set the connection timeout period, in seconds. The default value is 10.
  6. return $ossClient;
  7. }

Note: If an error occurs due to an SSL configuration exception (for example, “cURL error: SSL certificate problem” appears), replace https with http and initialize the OSS client.

  1. $uploadAddress['Endpoint'] = str_replace("https:", "http:", $uploadAddress['Endpoint']);

4. Upload a local file.

  1. function upload_local_file($ossClient, $uploadAddress, $localFile) {
  2. return $ossClient->uploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
  3. }

5. Update the upload credential.

  1. function refresh_upload_video($vodClient, $videoId) {
  2. $request = new vod\RefreshUploadVideoRequest();
  3. $request->setVideoId($videoId);
  4. return $vodClient->getAcsResponse($request);
  5. }
  • Execute the entire process (and capture exceptions):
  1. $accessKeyId = '<AccessKeyId>'; // Your AccessKey ID.
  2. $accessKeySecret = '<AccessKeySecret>'; // Your AccessKey Secret.
  3. $localFile = '/Users/yours/Video/testVideo.flv'; // The complete path of the local video file to be uploaded to ApsaraVideo for VOD.
  4. try {
  5. // Initialize the ApsaraVideo for VOD client and obtain the upload URL and credential.
  6. $vodClient = init_vod_client($accessKeyId, $accessKeySecret);
  7. $createRes = create_upload_video($vodClient);
  8. // If the execution is successful, VideoId, UploadAddress, and UploadAuth are returned.
  9. $videoId = $createRes->VideoId;
  10. $uploadAddress = json_decode(base64_decode($createRes->UploadAddress), true);
  11. $uploadAuth = json_decode(base64_decode($createRes->UploadAuth), true);
  12. // Use UploadAuth and UploadAddress to initialize the OSS client.
  13. $ossClient = init_oss_client($uploadAuth, $uploadAddress);
  14. // Upload the file. Note that multiple parts are uploaded in parallel. You must wait until all the parts have been uploaded before you can receive a successful response. The time consumed depends on the file size and uplink network bandwidth.
  15. //$result = upload_local_file($ossClient, $uploadAddress, $localFile);
  16. $result = multipart_upload_file($ossClient, $uploadAddress, $localFile);
  17. printf("Succeed, VideoId: %s", $videoId);
  18. } catch (Exception $e) {
  19. // var_dump($e);
  20. printf("Failed, ErrorMessage: %s", $e->getMessage());
  21. }

GO upload example

Environment requirements

  • Ensure that you have installed Go 1.7 or later. If Go is not installed, you can visit the Go official website to download and install an appropriate version.

Installation

  • Run the following go get command to install the SDK:
  1. go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk

Note:

  • No messages are displayed on the GUI during installation. Wait patiently. If the installation times out, run the command again.

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

  • Run the following glide command to install the SDK:

  1. glide get github.com/aliyun/alibaba-cloud-sdk-go

Reference code

  • Define the methods of the core steps:

1. Use the AccessKey to initialize the ApsaraVideo for VOD client.

  1. func InitVodClient(accessKeyId string, accessKeySecret string) (client *vod.Client, err error) {
  2. // Set the region of ApsaraVideo for VOD.
  3. regionId := "cn-shanghai"
  4. // Create an authorization object.
  5. credential := &credentials.AccessKeyCredential{
  6. accessKeyId,
  7. accessKeySecret,
  8. }
  9. // Customize configuration.
  10. config := sdk.NewConfig()
  11. config.AutoRetry = true // Indicates whether the system automatically retries to connect to ApsaraVideo for VOD upon a connection failure.
  12. config.MaxRetryTime = 3 // The maximum number of retries allowed.
  13. config.Timeout = 3000000000 // The connection timeout period, in nanoseconds. The default value 3000000000 indicates 3 seconds.
  14. // Create a vodClient instance.
  15. return vod.NewClientWithOptions(regionId, config, credential)
  16. }

2. Obtain the video upload URL and credential.

  1. func MyCreateUploadVideo(client *vod.Client) (response *vod.CreateUploadVideoResponse, err error) {
  2. request := vod.CreateCreateUploadVideoRequest()
  3. request.Title = "Sample Video Title"
  4. request.Description = "Sample Description"
  5. request.FileName = "/opt/video/sample/video_file.mp4"
  6. //request.CateId = "-1"
  7. request.CoverURL = "http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png"
  8. request.Tags = "tag1,tag2"
  9. request.AcceptFormat = "JSON"
  10. return client.CreateUploadVideo(request)
  11. }

3. Use the upload credential and URL to initialize the OSS client. Perform Base-64 decoding and JSON decoding before initialization.

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

4. Upload a local file.

  1. func UploadLocalFile(client *oss.Client, uploadAddressDTO UploadAddressDTO, localFile string) {
  2. // Obtain the bucket.
  3. bucket, err := client.Bucket(uploadAddressDTO.Bucket)
  4. if err ! = nil {
  5. fmt.Println("Error:", err)
  6. os.Exit(-1)
  7. }
  8. // Upload a local file.
  9. err = bucket.PutObjectFromFile(uploadAddressDTO.FileName, localFile)
  10. if err ! = nil {
  11. fmt.Println("Error:", err)
  12. os.Exit(-1)
  13. }
  14. }

5. Update the upload credential.

  1. func MyRefreshUploadVideo(client *vod.Client) (response *vod.RefreshUploadVideoResponse, err error) {
  2. request := vod.CreateRefreshUploadVideoRequest()
  3. request.VideoId = ""
  4. request.AcceptFormat = "JSON"
  5. return client.RefreshUploadVideo(request)
  6. }
  • Execute the entire process (and capture exceptions):
  1. type UploadAuthDTO struct {
  2. AccessKeyId string
  3. AccessKeySecret string
  4. SecurityToken string
  5. }
  6. type UploadAddressDTO struct {
  7. Endpoint string
  8. Bucket string
  9. FileName string
  10. }
  11. func main() {
  12. var accessKeyId string = "<AccessKeyId>"; // Your AccessKey ID.
  13. var accessKeySecret string = "<AccessKeySecret>"; // Your AccessKey Secret.
  14. var localFile string = "/Users/yours/Video/testVideo.flv"; // The complete path of the local video file to be uploaded to ApsaraVideo for VOD.
  15. // Initialize the ApsaraVideo for VOD client and obtain the upload URL and credential.
  16. var vodClient, initVodClientErr = InitVodClient(accessKeyId, accessKeySecret)
  17. if initVodClientErr ! = nil {
  18. fmt.Println("Error:", initVodClientErr)
  19. return
  20. }
  21. // Obtain the upload URL and credential.
  22. var response, createUploadVideoErr = MyCreateUploadVideo(vodClient)
  23. if createUploadVideoErr ! = nil {
  24. fmt.Println("Error:", createUploadVideoErr)
  25. return
  26. }
  27. // If the execution is successful, VideoId, UploadAddress, and UploadAuth are returned.
  28. var videoId = response.VideoId
  29. var uploadAuthDTO UploadAuthDTO
  30. var uploadAddressDTO UploadAddressDTO
  31. var uploadAuthDecode, _ = base64.StdEncoding.DecodeString(response.UploadAuth)
  32. var uploadAddressDecode, _ = base64.StdEncoding.DecodeString(response.UploadAddress)
  33. json.Unmarshal(uploadAuthDecode, &uploadAuthDTO)
  34. json.Unmarshal(uploadAddressDecode, &uploadAddressDTO)
  35. // Use UploadAuth and UploadAddress to initialize the OSS client.
  36. var ossClient, _ = InitOssClient(uploadAuthDTO, uploadAddressDTO)
  37. // Upload the file. Note that multiple parts are uploaded in parallel. You must wait until all the parts have been uploaded before you can receive a successful response. The time consumed depends on the file size and uplink network bandwidth.
  38. UploadLocalFile(ossClient, uploadAddressDTO, localFile)
  39. //MultipartUploadFile(ossClient, uploadAddressDTO, localFile)
  40. fmt.Println("Succeed, VideoId:", videoId)
  41. }

Demo download

PHP upload SDK demo

You can download the completesource code of PHP upload SDK demo .For more information, see File upload by using OSS-PHP-SDK.

GO upload SDK demo

You can download the completesource code of Go upload SDK demo .For more information, see File upload by using OSS-GO-SDK.

Demos of upload SDKs in other languages

  • For more information about how to download demos of upload SDKs in other languages, see SDK download.