The ApsaraVideo VOD upload SDK allows you to quickly upload media files. This topic provides an example to describe how to use the upload SDK for Java.

Features

The upload SDK for Java provides the following major features:
  • Allows you to upload local audio or video files: By default, multipart upload is used. You can upload a file of up to 48.8 TB in size. Resumable upload is supported.
  • Allows you to upload online video or audio files: After you specify the URL of an online video or audio file, the system automatically downloads the file from the URL, and then uploads the file to ApsaraVideo VOD. You can upload a file of up to 48.8 TB in size.
  • Allows you to upload local images: After you specify the local directory of an image, the system automatically uploads the image to ApsaraVideo VOD.
  • Allows you to upload online images: After you specify the URL of an online image, the system automatically downloads the image from the URL and then uploads the image to ApsaraVideo VOD.
  • Allows you to upload local M3U8 video or audio files (including all segment files): After you specify the local directories of the M3U8 files and segment files, the system automatically uploads local M3U8 video or audio files (including all segment files) to ApsaraVideo VOD.
  • Allows you to upload online M3U8 video or audio files (including all segment files): After you specify the URLs of the M3U8 files and segment files, the system automatically uploads online M3U8 video or audio files (including all segment files) to ApsaraVideo VOD.
  • Allows you to upload local auxiliary media assets: After you specify the local directory of an auxiliary media asset, the system automatically uploads the asset to ApsaraVideo VOD.
  • Allows you to upload online auxiliary media assets: After you specify the URL of an auxiliary media asset, the system automatically downloads the asset from the URL, and then uploads the asset to ApsaraVideo VOD.
Note Before you can use an upload URL to upload files, you must encode the upload URL. This way, upload failures caused by special characters in the URL can be avoided. The URL-based upload is only available only in the China (Shanghai) region.
The upload SDK for Java provides the following additional features:
  • Provides a progress bar for uploads and supports the callbacks for the default and custom upload progress. This feature is unavailable when you upload M3U8 files.
  • Allows you to specify the region of an Elastic Compute Service (ECS) instance on which you want to deploy the upload script. If the region of the ECS instance is the same as the storage region in ApsaraVideo VOD, the specified file is automatically uploaded over the internal network. This helps accelerate uploads and consume less Internet traffic. ApsaraVideo VOD provides only public endpoints for you to use APIs. Therefore, you must use an ECS instance that can be accessed over the Internet to deploy an upload script.
  • Allows you to specify the VOD center and storage region to facilitate uploads that originate outside mainland China. The default VOD center is in the China (Shanghai) region.
  • Allows you to specify the metadata (title), storage location, user data, transcoding template, and media workflow for the upload.
  • Supports access using the Security Token Service (STS). Specific API operations are required to obtain and specify STS tokens. If the STS token expires during the upload, the SDK periodically requests a new STS token, and then sends the token to the server to resume the upload.

For more information about file formats that are supported by ApsaraVideo VOD, see Overview.

Prerequisites

  • An Alibaba Cloud account is created. Real-name verification is complete for the Alibaba Cloud account.
  • The server is configured to use Java 1.8.

Install the SDK

Note In this topic, Java 1.8 and upload SDK V1.4.14 for Java are used as examples. You can use other versions based on your business requirements.
  1. Download the VODUploadDemo-java-1.4.14.zip package, which contains the upload SDK for Java and sample code. For more information, see SDK download.
  2. Decompress the VODUploadDemo-java-1.4.14.zip package.
    File introduction:
    • lib: stores JAR packages that are required by the upload SDK for Java.
    • sample: stores the sample code of the upload SDK for Java.
  3. Import JAR packages.
    Notice After you import JAR packages, you must configure dependencies.

    Eclipse and IntelliJ IDEA are used as examples to describe how to import JAR packages.

    • In Eclipse, right-click your project name and choose Properties > Java Build Path > Add JARs.
    • In IntelliJ IDEA, select your project and choose File > Project Structure > Modules. On the right-side of the Dependencies tab, click the + icon and select JARs or directories.

    Find the decompressed VODUploadDemo-java-1.4.14 package and add all JAR files in the lib directory to your project.

  4. Configure dependencies.
    Notice Make sure that the specific JAR packages meet the following requirements:
    • If you use the aliyun-java-vod-upload-1.4.14.jar package to install the upload SDK for Java, you must use aliyun-sdk-oss V3.9.0 or later.
    • ApsaraVideo VOD has been released in the China (Shanghai), China (Beijing), and China (Shenzhen) regions. If you want to use the upload SDK for Java to upload files to the China (Shenzhen) and China (Beijing) regions, you must use aliyun-java-sdk-vod V2.15.11 or later and aliyun-java-sdk-core V4.4.5 or later.

    You must add the following Maven dependencies.

       <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>
         <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-vod</artifactId>
            <version>2.15.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>

Sample code

Notice If you use the sample code, you must manually import the corresponding class.

If the related dependencies cannot be found during code execution, see FAQ.

  • Sample code of the upload SDK

    The UploadVideoDemo.java file in the sample directory is used as the sample code of the upload SDK.

    The following section lists part of the sample code. For the complete sample code, see the UploadVideoDemo.java file.

    public class UploadVideoDemo {
    
        // Required. Enter the AccessKey ID of your Alibaba Cloud account.
        private static final String accessKeyId = "<your accessKeyId>";
        // Required. Enter the AccessKey secret of your Alibaba Cloud account.
        private static final String accessKeySecret = "<your accessKeySecret>";
    
        public static void main(String[] args) {
            // Upload video files.
            // Required. The title of the file.
            String title = "Test";
            // 1.Required. When you upload a local file or a file stream, set the file name to the absolute path of the file, such as /User/sample/file name.mp4.
            // 2.Required. When you upload an online file, set the file name to the source file name, such as file name.mp4. 
            // The names of all files that you upload must contain a filename extension.
            String fileName = "/path /file name.mp4";
            // Upload a local file.
            //testUploadVideo(accessKeyId, accessKeySecret, title, fileName);
    
            // The URL of the online file that you want to upload.
            String url = "http://xxxx.xxxx.com/xxxx.mp4";
    
            // 2.Upload an online file.
            // If the URL does not contain a filename extension, specify a filename extension.
            String fileExtension = "mp4";
            //testUploadURLStream(accessKeyId, accessKeySecret, title, url, fileExtension);
    
            // Upload images.
            //testUploadImageLocalFile(accessKeyId, accessKeySecret);
    
        }
    
    
        /**
         * Specify the API operation that is used to upload local files.
         *
         * @param accessKeyId
         * @param accessKeySecret
         * @param title
         * @param fileName
         */
        private static void testUploadVideo(String accessKeyId, String accessKeySecret, String title, String fileName) {
            UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
            /* Specify the size of each part in multipart upload. Default value: 2. Unit: MB. */
            request.setPartSize(2 * 1024 * 1024L);
            /* Specify the number of concurrent threads for multipart upload. The default value is 1. This setting consumes CPU resources of the server. You can specify a value based on your server load. */
            request.setTaskNum(1);
            /* Specify whether to enable resumable upload. By default, resumable upload is disabled. If the upload is paused due to a network disconnection or program crash, you can send an upload request again to resume the upload. Resumable upload is suitable for large files that cannot be completely uploaded within the timeout period of 3,000 seconds. 
            Note: If you enable resumable upload, the upload progress is written to a local disk file during the upload. This slows down the upload. We recommend that you specify whether to enable resumable upload based on your business requirements. */
            //request.setEnableCheckpoint(false);
            /* Specify the timeout period of Object Storage Service (OSS) slow requests for each part. If the system takes more time than the specified timeout period to upload a part, a debug log is generated. You can adjust the threshold to prevent generating debug logs. Unit: milliseconds. Default value: 300000. */
            //request.setSlowRequestsThreshold(300000L);
            /* Specify the timeout period of slow requests for each part. By default, the timeout period is 300 seconds. */
            //request.setSlowRequestsThreshold(300000L);
            /* Optional. Specifies whether to display the watermark. When you specify the ID of the template group, determine whether to display the watermark based on the configuration of the template group. */
            //request.setIsShowWaterMark(true);
            /* Optional. Customize the callback configuration for event notifications. For more information about the parameters, see Request parameters. */
            // request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}");
            /* Optional. Specify the category ID of the video. */
            //request.setCateId(0);
            /* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
            //request.setTags("tag 1,tag 2");
            /* Optional. Specify the description of the video. */
            //request.setDescription("Video description");
            /* Optional. Specify the thumbnail of the video. */
            //request.setCoverURL("http://cover.sample.com/sample.jpg");
            /* Optional. Specify the ID of the template group. */
            //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56a33d");
            /* Optional. Specify the ID of the workflow. */
            //request.setWorkflowId("d4430d07361f0*be1339577859b0177b");
            /* Optional. Specify the storage region. */
            //request.setStorageLocation("in-201703232118266-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
            /* Enable the callback for the default upload progress. */
            //request.setPrintProgress(false);
            /* Specify the callback for the custom upload progress. The callback must inherit VoDProgressListener. */
            //request.setProgressListener(new PutObjectProgressListener());
            /* Specify an API operation to generate the STS information. */
            // request.setVoDRefreshSTSTokenListener(new RefreshSTSTokenImpl());
            /* Specify the ID of the application. */
            //request.setAppId("app-1000000");
            /* Specify the access region of ApsaraVideo VOD. */
            //request.setApiRegionId("cn-shanghai");
            /* Specify the region where the ECS instance is deployed. */
            // request.setEcsRegionId("cn-shanghai");
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadVideoResponse response = uploader.uploadVideo(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n"); // Specify the ID of the request that is sent to ApsaraVideo VOD.
            if (response.isSuccess()) {
                System.out.print("VideoId=" + response.getVideoId() + "\n");
            } else {
                /* If the callback URL that you specify is invalid, video upload is not affected. The video ID is returned with the error code. If the upload fails in other cases, the video ID is left empty. Analyze the cause based on the returned error code. */
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            }
        }
    
        /**
         * Use URLs to upload online files. Resumable upload is supported. You can upload a file of up to 48.8 TB in size. 
         * Before you upload online files, you must download the files to a local disk. Make sure that the local disk has sufficient space. 
         * If the URL that you specify does not contain a filename extension, configure the fileExtension parameter. 
         * @param accessKeyId
         * @param accessKeySecret
         * @param title
         * @param fileName
         * @param url
         */
        private static void testUploadURLStream(String accessKeyId, String accessKeySecret, String title, String url, String fileExtension) {
            UploadURLStreamRequest request = new UploadURLStreamRequest(accessKeyId, accessKeySecret, title, url);
    
            /* Specify the filename extension. */
            request.setFileExtension(fileExtension);
            /* Specify the timeout period of the connection that is established to download online files. Unit: milliseconds. The value 0 indicates no timeout period. */
            request.setDownloadConnectTimeout(1000);
            /* Specify the timeout period of read for downloading online files. Unit: milliseconds. The value 0 indicates no timeout period. */
            request.setDownloadReadTimeout(0);
            /* Specify a local directory to store online files. */
            request.setLocalDownloadFilePath("/Users/download");
            /* Optional. Specifies whether to display the watermark. When you specify the ID of the template group, determine whether to display the watermark based on the configuration of the template group. */
            //request.setShowWaterMark(true);
            /* Optional. Customize the callback configuration for event notifications. For more information about the parameters, see Request parameters. */
            // request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}");
            /* Optional. Specify the category ID of the video. */
            //request.setCateId(0);
            /* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
            //request.setTags("tag 1,tag 2");
            /* Optional. Specify the description of the video. */
            //request.setDescription("Video description");
            /* Optional. Specify the thumbnail of the video. */
            //request.setCoverURL("http://cover.sample.com/sample.jpg");
            /* Optional. Specify the ID of the template group. */
            //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56a33d");
            /* Optional. Specify the ID of the workflow. */
            //request.setWorkflowId("d4430d07361f0*be1339577859b0177b");
            /* Optional. Specify the storage region. */
            //request.setStorageLocation("xxxxxx.oss-cn-shanghai.aliyuncs.com");
            /* Enable the callback for the default upload progress. */
            //request.setPrintProgress(true);
            /* Specify the callback for the custom upload progress. The callback must inherit VoDProgressListener. */
            //request.setProgressListener(new PutObjectProgressListener());
            /* Specify the ID of the application. */
            //request.setAppId("app-1000000");
            /* Specify the access region of ApsaraVideo VOD. */
            //request.setApiRegionId("cn-shanghai");
            /* Specify the region where the ECS instance is deployed. */
            // request.setEcsRegionId("cn-shanghai");
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadURLStreamResponse response = uploader.uploadURLStream(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n"); // Specify the ID of the request that is sent to ApsaraVideo VOD.
            if (response.isSuccess()) {
                System.out.print("VideoId=" + response.getVideoId() + "\n");
            } else {
                /* If the callback URL that you specify is invalid, video upload is not affected. The video ID is returned with the error code. If the upload fails in other cases, the video ID is left empty. Analyze the cause based on the returned error code. */
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            }
        }
    
        /**
         * Specify an API operation that is used to upload local images.
         * For more information about the parameters, see CreateUploadImage.
         *
         * @param accessKeyId
         * @param accessKeySecret
         */
        private static void testUploadImageLocalFile(String accessKeyId, String accessKeySecret) {
            // Required. Specify the type of the image. Valid values: default, cover, and watermark. */
            String imageType = "default";
            UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
            request.setImageType("default");
            /* Optional. Specify the filename extension of the image. Valid values: png, jpg, and jpeg. */
            //request.setImageExt("png");
            /* Optional. Specify the title of the image. A title cannot exceed 128 bytes in length. Encode the title in UTF-8. */
            // request.setTitle("Image title");
            /* Optional. Specify the tags of the image. A tag can be up to 32 bytes in length. You can enter up to 16 tags. Separate multiple tags with commas (,). Encode the tags in UTF-8. */
            //request.setTags("tag 1,tag 2");
            /* Optional. Specify the storage region. */
            //request.setStorageLocation("out-4f3952f78c0211e8b3020013e7.oss-cn-shanghai.aliyuncs.com");
            /* Set fileName to the source file name, such as file name.png. */
            String fileName = "/User/sample/ file name.png";
            request.setFileName(fileName);
            /* Enable the callback for the default upload progress. */
            //request.setPrintProgress(false);
            /* Specify the callback for the custom upload progress. The callback must inherit VoDProgressListener. */
            // request.setProgressListener(new PutObjectProgressListener());
            /* Specify the ID of the application. */
            //request.setAppId("app-1000000");
            /* Specify the access region of ApsaraVideo VOD. */
            //request.setApiRegionId("cn-shanghai");
            UploadImageImpl uploadImage = new UploadImageImpl();
            UploadImageResponse response = uploadImage.upload(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n");
            if (response.isSuccess()) {
                System.out.print("ImageId=" + response.getImageId() + "\n");
                System.out.print("ImageURL=" + response.getImageURL() + "\n");
            } else {
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            }
        }
    }                   
    The following steps show how to obtain the AccessKey secret.
    1. Go to the AccessKey Pair page.
    2. Select the AccessKey ID that you want to use and click View Secret. After you complete the phone verification, you can obtain the AccessKey secret.
  • Sample code of the upload progress bar

    The PutObjectProgressListener.java file in the sample directory is the sample code of the callback function for the upload progress.

    The class must inherit the VoDProgressListener class. ProgressEvent indicates an event that is generated to notify you of the upload progress when you upload a file to OSS. You can customize the business processing logic for different event notifications.

    The following sample code is for your reference.

    /**
     * Specify the class of callbacks for the upload progress.
     * The callback takes effect only when you enable the callback for the upload progress. 
     * A callback is triggered when the OSS multipart upload succeeds or fails. You can handle event callbacks based on the business processing logic. 
     * After the video or audio information is created, the value of the videoId parameter in the callback for the upload progress is the video ID that is generated in the current upload. You can manage video and audio files based on the video IDs. 
     * After the image information is created, the value of the ImageId parameter in the callback for the upload progress is the image ID that is generated in the current upload. You can manage images based on the image IDs. 
     */
    
    public class PutObjectProgressListener implements VoDProgressListener {
        /**
         * The number of bytes that have been uploaded to OSS.
         */
        private long bytesWritten = 0;
        /**
         * The total size of the source file. Unit: bytes.
         */
        private long totalBytes = -1;
        /**
         * Specify whether the current upload is successful.
         */
        private boolean succeed = false;
        /**
         * The ID of the video.
         */
        private String videoId;
        /**
         * The ID of the image.
         */
        private String imageId;
    
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
                // The event notification indicates that the upload starts.
                case TRANSFER_STARTED_EVENT:
                    if (videoId != null) {
                        System.out.println("Start to upload videoId "+videoId+"......");
                    }
                    if (imageId != null) {
                        System.out.println("Start to upload imageId "+imageId+"......");
                    }
                    break;
                // The event notification indicates the total size of the file that you want to upload. Unit: bytes. The event is supported only in the upload of local files.
                case REQUEST_CONTENT_LENGTH_EVENT:
                    this.totalBytes = bytes;
                    System.out.println(this.totalBytes + "bytes in total will be uploaded to OSS.");
                    break;
                // The event notification indicates the size of uploaded files. Unit: bytes.
                case REQUEST_BYTE_TRANSFER_EVENT:
                    this.bytesWritten += bytes;
                    if (this.totalBytes != -1) {
                        int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                        System.out.println(bytes+" bytes have been written at this time, upload progress: "+
                                percent +"%(" +  this.bytesWritten +  "/"  + this.totalBytes  + ")");
                    } else {
                        System.out.println(bytes + " bytes have been written at this time, upload sub total : " +
                                "(" + this.bytesWritten + ")");
                    }
                    break;
                // The event notification indicates that all files have been uploaded.
                case TRANSFER_COMPLETED_EVENT:
                    this.succeed = true;
                    if (videoId != null) {
                        System.out.println("Succeed to upload videoId "  + videoId  + " , " + this.bytesWritten + " bytes have been transferred in total.");
                    }
                    if (imageId != null) {
                        System.out.println("Succeed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred in total.");
                    }
                    break;
                // The event notification indicates that the upload fails.
                case TRANSFER_FAILED_EVENT:
                    if (videoId != null) {
                        System.out.println("Failed to upload videoId " + videoId + " , " + this.bytesWritten + " bytes have been transferred.");
                    }
                    if (imageId != null) {
                        System.out.println("Failed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred.");
                    }
                    break;
    
                default:
                    break;
            }
        }
    
        public boolean isSucceed() {
            return succeed;
        }
    
        public void onVidReady(String videoId) {
            setVideoId(videoId);
        }
    
        public void onImageIdReady(String imageId) {
            setImageId(imageId);
        }
    
        public String getVideoId() {
            return videoId;
        }
    
        public void setVideoId(String videoId) {
            this.videoId = videoId;
        }
    
        public String getImageId() {
            return imageId;
        }
    
        public void setImageId(String imageId) {
            this.imageId = imageId;
        }
    }
                        
  • Sample code used to refresh temporary tokens

    The RefreshSTSTokenImpl.java file in the sample directory is the sample code that you can use to refresh temporary tokens.

    The following sample code is for your reference.

    /**
     * @author vod
     * Specify the implementation class that is used to generate STS information.
     * @date 2019/6/5
     */
    public class RefreshSTSTokenImpl implements VoDRefreshSTSTokenListener {
    
        public STSTokenDTO onRefreshSTSToken() {
            STSTokenDTO stsTokenDTO = new STSTokenDTO();
            stsTokenDTO.setAccessKeyId("<your sts AccessKeyId>");
            stsTokenDTO.setAccessKeySecret("<your sts AccessKeySecret>");
            stsTokenDTO.setSecurityToken("<your sts SecurityToken>");
            return stsTokenDTO;
        }
    
    }

FAQ

What do I do if the related dependencies cannot be found?

In most cases, this issue is caused by compilation in the IntelliJ IDEA development environment. If the required resource packages are imported, you can attempt to resolve the issue by using one of the following methods:
  • In the Maven project, click Maven in the upper-right corner. Then click the m icon and enter mvn idea:module to reload resources. module
  • In the top navigation bar, choose Build > Rebuild Project to edit your project. Rebuild