All Products
Search
Document Center

ApsaraVideo VOD:Use the upload SDK for Java to upload files

Last Updated:Jan 23, 2024

This topic describes how to use the upload SDK for Java to upload media files to ApsaraVideo VOD.

Overview

The upload SDK for Java follows the general process of ApsaraVideo VOD SDKs. For more information, see Upload process. The process includes the following steps:

  1. Complete the configurations as described in the Prerequisites section of this topic. For more information, see Prerequisites.

  2. Integrate the upload SDK for Java. For more information, see Integrate the upload SDK for Java.

  3. Implement the upload logic by configuring upload information.

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.

  • 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.

Integrate the upload SDK for Java

Note

In the following example, Java 1.8 or later and the upload SDK for Java V1.4.15 are used. You can use other versions based on your business requirements. You cannot integrate the upload SDK by directly adding dependencies. You must download and import JAR packages to your project. For more information about how to troubleshoot the errors that may occur when you integrate the upload SDK for Java, see Troubleshooting.

  1. Download the package that contains the upload SDK for Java and sample code.

    Note
    • For more information about the download link of the upload SDK for Java of the latest version, see SDK download. For more information about the download links of the upload SDK for Java of historical versions, see Release notes for the upload SDK for Java.

    • For more information about the complete sample code, see the sample/UploadVideoDemo.java file in the directory in which you decompress the package of the upload SDK for Java.

  2. Decompress the package.

    The package VODUploadDemo-java-1.4.15.zip is used in this example. The following subfolders are extracted from the package:

    • lib: stores JAR packages of the upload SDK for Java.

    • sample: stores the sample code of the upload SDK for Java.

  3. Import JAR packages.

    • In Eclipse, right-click your project name and choose Properties > Java Build Path > Add JARs. Find the decompressed VODUploadDemo-java-1.4.15 folder and add all JAR packages in lib to your project.

    • In IntelliJ IDEA, open 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.15 folder and add all JAR packages in lib to your project.

    Important

    After you import JAR packages, you must configure dependencies.

  4. Add dependencies such as Alibaba Cloud SDK for Java, Object Storage Service (OSS) SDK, ApsaraVideo VOD SDK, and ApsaraVideo VOD server upload SDK.

    Important
    • You must integrate all the preceding dependencies. Otherwise, the integration fails.

    • If you download the latest version of the package aliyun-java-vod-upload-1.4.15.jar, make sure that the version of aliyun-sdk-oss is V3.9.0 or later and the version of aliyun-java-sdk-vod is V2.16.11 or later.

    • ApsaraVideo VOD is supported in the China (Shanghai), China (Shenzhen), and China (Beijing) regions. If you use the upload SDK for Java V1.4.14 or earlier to upload media files to the China (Shenzhen) or China (Beijing) region, you must use aliyun-java-sdk-vod V2.15.11 or later and aliyun-java-sdk-core V4.4.5 or later. If you use the upload SDK for Java V1.4.15 or later to upload media files to the China (Shenzhen) or China (Beijing) region, you must use aliyun-java-sdk-vod V2.16.11 or later and aliyun-java-sdk-core V4.4.5 or later.

    Show 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.16.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68.noneautotype</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>
        <dependency>
            <groupId>com.aliyun.vod</groupId>
            <artifactId>upload</artifactId>
            <version>1.4.15</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/aliyun-java-vod-upload-1.4.15.jar</systemPath>
        </dependency>
                            

Scenario 1: Upload audio or video files

Regular audio or video files

ApsaraVideo VOD allows you to upload audio or video files by using one of the following methods:

  • Use multipart upload to upload a local audio or video file. You can enable resumable upload when you use this method. For more information, see the testUploadVideo function in the sample code.

    • An upload job can run for up to 3,000 seconds if resumable upload is not enabled. In this case, the maximum size of a file that can be uploaded varies based on the network bandwidth and the read and write capacities of disks.

    • If you enable resumable upload, you can upload a file of up to 48.8 TB in size.

      Important

      After you enable resumable upload, ApsaraVideo VOD writes the upload progress to a local disk file during the upload. This affects the upload speed. You can choose to enable the resumable upload feature based on your file size.

  • Upload a network stream. You can use this method to upload online audio or video files by using the file URLs. Resumable upload is supported for this method. 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. For more information, see the testUploadURLStream function in the sample code.

  • Upload a file stream. You can use this method to upload specified local files. Resumable upload is not supported for this method. You can upload a file of up to 5 GB in size. For more information, see the testUploadFileStream function in the sample code.

  • Use streaming upload. You can use this method to upload specified streams, such as file streams and network streams. Resumable upload is not supported for this method. You can upload a file of up to 5 GB in size. For more information, see the testUploadStream function in the following sample code.

Important

If you use the sample code, you must import the corresponding classes. If the related dependencies cannot be found when you execute the code, see Troubleshooting.

Show sample code

public class UploadVideoDemo {
    // Required. Enter the AccessKey pair of your Alibaba Cloud account.
    // 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 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. 
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    public static void main(String[] args) {
    // Upload a video file.
    // Required. Specify the title of the file.
    String title = "Test";
    // 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. The file name is required.
    // When you upload an online file, set the file name to the name of the source file, such as File name.mp4. The file name is required. 
    // When you use streaming upload, set the file name to the name of the source file, such as File name.mp4. The file name is required. 
    // The name of each file that you upload must contain a file name extension.
    String fileName = "/Users/test/video/test.mp4";
    // Upload a local file.
    testUploadVideo(accessKeyId, accessKeySecret, title, fileName);

    // Specify the URL of the online file that you want to upload.
    String url = "http://test.aliyun.com/video/test.mp4";

    // Upload a network stream.
    // If the URL does not contain a file name extension, specify a file name extension.
    String fileExtension = "mp4";
    testUploadURLStream(accessKeyId, accessKeySecret, title, url, fileExtension);

    // Upload a file stream.
    testUploadFileStream(accessKeyId, accessKeySecret, title, fileName);

    // Use streaming upload to upload a file stream or a network stream.
    InputStream inputStream = null;
    // Upload a file stream.
    try {
        inputStream = new FileInputStream(fileName);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // Upload a network stream.
    try {
        inputStream = new URL(url).openStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    testUploadStream(accessKeyId, accessKeySecret, title, fileName, inputStream);
}

/**
 * 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. Concurrent threads consume the 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 network disconnections or program crashes, you can resend an upload request to resume the upload. Resumable upload is suitable for large files that cannot be completely uploaded within a timeout period of 3,000 seconds. 
    Note: After you enable resumable upload, the upload progress is written to a local disk file during the upload. This affects the upload speed. Specify whether to enable resumable upload based on your business requirements. */
    //request.setEnableCheckpoint(false);
    /* Specify the timeout period of OSS slow requests for each part. If the system takes longer than the specified timeout period to upload a part, a debug log is generated. You can adjust the threshold to prevent debug log generation. The default timeout period is 300,000 milliseconds.*/
    //request.setSlowRequestsThreshold(300000L);
    /* Specify the timeout period of slow requests for each part. The default timeout period is 300 seconds. */
    //request.setSlowRequestsThreshold(300000L);
    /* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
    //request.setIsShowWaterMark(true);
    /* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.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.example.com/image_01.jpg");
    /* Optional. Specify the ID of the template group that is used for the video. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e5****");
    /* Optional. Specify the ID of the workflow. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. Specify the storage location. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enable the default callback for the upload progress. */
    //request.setPrintProgress(false);
    /* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
    /* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* Specify the class that is used to generate the Security Token Service (STS) information. */
    // request.setVoDRefreshSTSTokenListener(new RefreshSTSTokenImpl());
    /* Specify the ID of the application. */
    //request.setAppId("app-100****");
    /* Specify the access region of ApsaraVideo VOD. */
    //request.setApiRegionId("cn-shanghai");
    /* Specify the region in which the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");

    /* Optional. Configure a proxy. */
    //OSSConfig ossConfig = new OSSConfig();
    /* Required. Specify the address of the proxy server. */
    //ossConfig.setProxyHost("<yourProxyHost>");
    /* Required. Specify the port that is used to connect to the proxy server. */
    //ossConfig.setProxyPort(-1);
    /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
    //ossConfig.setProtocol("HTTP");
    /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
    //ossConfig.setUserAgent("<yourUserAgent>");
    /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
    //ossConfig.setProxyUsername("<yourProxyUserName>");
    /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
    //ossConfig.setProxyPassword("<yourProxyPassword>");
    //request.setOssConfig(ossConfig);

    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 video ID is empty, the upload fails. 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 file name extension, specify the fileExtension parameter. 
 * @param accessKeyId
 * @param accessKeySecret
 * @param title
 * @param fileExtension
 * @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 file name 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 limit. */
    request.setDownloadConnectTimeout(1000);
    /* Specify the timeout period for reading online files. Unit: milliseconds. The value 0 indicates no limit. */
    request.setDownloadReadTimeout(0);
    /* Specify a local directory to store online files. */
    request.setLocalDownloadFilePath("/Users/download");
    /* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
    //request.setShowWaterMark(true);
    /* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.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.example.com/image_01.jpg");
    /* Optional. Specify the ID of the template group that is used for the video. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* Optional. Specify the ID of the workflow. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. Specify the storage location. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enable the default callback for the upload progress. */
    //request.setPrintProgress(true);
    /* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
    /* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* Specify the ID of the application. */
    //request.setAppId("app-100****");
    /* Specify the access region of ApsaraVideo VOD. */
    //request.setApiRegionId("cn-shanghai");
    /* Specify the region in which the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");

     /* Optional. Configure a proxy. */
     //OSSConfig ossConfig = new OSSConfig();
     /* Required. Specify the address of the proxy server. */
     //ossConfig.setProxyHost("<yourProxyHost>");
     /* Required. Specify the port that is used to connect to the proxy server. */
     //ossConfig.setProxyPort(-1);
     /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
     //ossConfig.setProtocol("HTTP");
     /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("<yourUserAgent>");
     /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
     //ossConfig.setProxyUsername("<yourProxyUserName>");
     /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
     //ossConfig.setProxyPassword("<yourProxyPassword>");
     //request.setOssConfig(ossConfig);

    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 video ID is empty, the upload fails. 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 the API operation that is used to upload a file stream.
 *
 * @param accessKeyId
 * @param accessKeySecret
 * @param title
 * @param fileName
 */
private static void testUploadFileStream(String accessKeyId, String accessKeySecret, String title, String fileName) {
    UploadFileStreamRequest request = new UploadFileStreamRequest(accessKeyId, accessKeySecret, title, fileName);
    /* Optional. Specify whether to use the default watermark based on the configuration of the template group. */
    //request.setShowWaterMark(true);
    /* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.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.example.com/image_01.jpg");
    /* Optional. Specify the ID of the template group that is used for the video. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* Optional. Specify the ID of the workflow. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. Specify the storage location. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enable the default callback for the upload progress. */
    //request.setPrintProgress(true);
    /* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
    /* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* Specify the ID of the application. */
    //request.setAppId("app-100****");
    /* Specify the access region of ApsaraVideo VOD. */
    //request.setApiRegionId("cn-shanghai");
    /* Specify the region in which the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");

     /* Optional. Configure a proxy. */
     //OSSConfig ossConfig = new OSSConfig();
     /* Required. Specify the address of the proxy server. */
     //ossConfig.setProxyHost("<yourProxyHost>");
     /* Required. Specify the port that is used to connect to the proxy server. */
     //ossConfig.setProxyPort(-1);
     /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
     //ossConfig.setProtocol("HTTP");
     /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("<yourUserAgent>");
     /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
     //ossConfig.setProxyUsername("<yourProxyUserName>");
     /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
     //ossConfig.setProxyPassword("<yourProxyPassword>");
     //request.setOssConfig(ossConfig);

    UploadVideoImpl uploader = new UploadVideoImpl();
    UploadFileStreamResponse response = uploader.uploadFileStream(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 video ID is empty, the upload fails. 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 the API operation that is used for streaming upload.
 *
 * @param accessKeyId
 * @param accessKeySecret
 * @param title
 * @param fileName
 * @param inputStream
 */
private static void testUploadStream(String accessKeyId, String accessKeySecret, String title, String fileName, InputStream inputStream) {
    UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
     /* Optional. Specify whether to use the default watermark based on the configuration of the template group. */
    //request.setShowWaterMark(true);
    /* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.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.example.com/image_01.jpg");
    /* Optional. Specify the ID of the template group that is used for the video. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* Optional. Specify the ID of the workflow. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. Specify the storage location. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enable the default callback for the upload progress. */
    // request.setPrintProgress(true);
    /* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
    /* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
    // request.setProgressListener(new PutObjectProgressListener());
     /* Specify the ID of the application. */
    //request.setAppId("app-100****");
    /* Specify the access region of ApsaraVideo VOD. */
    //request.setApiRegionId("cn-shanghai");
    /* Specify the region in which the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");

     /* Optional. Configure a proxy. */
     //OSSConfig ossConfig = new OSSConfig();
     /* Required. Specify the address of the proxy server. */
     //ossConfig.setProxyHost("<yourProxyHost>");
     /* Required. Specify the port that is used to connect to the proxy server. */
     //ossConfig.setProxyPort(-1);
     /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
     //ossConfig.setProtocol("HTTP");
     /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("<yourUserAgent>");
     /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
     //ossConfig.setProxyUsername("<yourProxyUserName>");
     /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
     //ossConfig.setProxyPassword("<yourProxyPassword>");
     //request.setOssConfig(ossConfig);
        
    UploadVideoImpl uploader = new UploadVideoImpl();
    UploadStreamResponse response = uploader.uploadStream(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 and an error code are returned. If the upload failure is not caused by an invalid callback URL, the ID of the video is empty. Identify the cause of the error 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");
    }
  }
}

M3U8 files

Show sample code

public class UploadVideoDemo {
    // Required. Enter the AccessKey pair of your Alibaba Cloud account.
    // 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 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. 
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    public static void main(String[] args) {
    // Upload an M3U8 file.
        // Upload a local M3U8 audio or video file.
        testUploadLocalM3u8(accessKeyId, accessKeySecret);
        // Upload an online M3U8 audio or video file.
        testUploadWebM3u8(accessKeyId, accessKeySecret);
    }
    /**
     * Upload a local M3U8 audio or video file to ApsaraVideo VOD. By default, the M3U8 file and the .ts parts are stored in the same directory. If you leave the sliceFilenames parameter empty, the path of the M3U8 file is parsed to obtain the paths of the .ts parts.
     *
     * @param request The request class for uploading local M3U8 files.
     *                m3u8Filename: the absolute path of the local M3U8 index file. The part information in the M3U8 file must contain relative paths and cannot contain URLs or absolute local paths.
     *                sliceFilenames: the absolute paths of the .ts parts. If you leave this parameter empty, ApsaraVideo VOD automatically parses the path of the M3U8 file specified by the m3u8Filename parameter.
     */
    private static void testUploadLocalM3u8(String accessKeyId, String accessKeySecret) {
        String title = "test_upload_local_m3u8";
        String m3u8Filename = "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/cc38da35c7b24de0abe58619cdd7****-6479a12446b994719838e0307f****-ld.m3u8";
        UploadLocalM3u8Request request = new UploadLocalM3u8Request(accessKeyId, accessKeySecret, title, m3u8Filename);
        String[] sliceFilenames = new String[]{
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00001.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00002.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00003.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00004.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00005.ts"
        };
        // Optional. The list of .ts parts. If you leave this parameter empty, ApsaraVideo VOD automatically parses the m3u8FileURL parameter to obtain the paths of the .ts parts.
        request.setSliceFilenames(sliceFilenames);
        /* 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. Concurrent threads consume the CPU resources of the server. You can specify a value based on your server load. */
        request.setTaskNum(1);
        /* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
        //request.setShowWaterMark(true);
        /* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
        //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
        /* Optional. Specify the category ID of the video. */
        //request.setCateId(-1L);
        /* 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 that is used for the video. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* Optional. Specify the ID of the workflow. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* Optional. Specify the storage location. */
        //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
        /* Specify the ID of the application. */
        // request.setAppId("app-1000000");
        /* Specify the access region of ApsaraVideo VOD. */
        // request.setApiRegionId("cn-shanghai");
        /* Specify the region in which the ECS instance is deployed. */
        // request.setEcsRegionId("cn-shanghai");

        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. Specify the address of the proxy server. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. Specify the port that is used to connect to the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        
        UploadM3u8FileImpl uploadM3u8File = new UploadM3u8FileImpl();
        UploadLocalM3u8Response uploadLocalM3u8Response = uploadM3u8File.uploadLocalM3u8(request);
        System.out.println("code = " + uploadLocalM3u8Response.getCode());
        System.out.println("message = " + uploadLocalM3u8Response.getMessage());
        System.out.println("videoId = " + uploadLocalM3u8Response.getVideoId());
        System.out.println("requestId = " + uploadLocalM3u8Response.getRequestId());
    }

    /**
     * Upload an online M3U8 audio or video file to ApsaraVideo VOD. Before you upload online M3U8 audio or video files, you must download the files to a local disk. Make sure that the local disk has sufficient space.
     *
     * @param request The request class for uploading online M3U8 files.
     *                m3u8FileURL: the URL of the online M3U8 index file. The part information in the M3U8 file must contain relative paths and cannot contain URLs or absolute local paths.
     *                sliceFileURLs: the URLs of the .ts parts. You must manually assemble the URLs.
     */
    private static void testUploadWebM3u8(String accessKeyId, String accessKeySecret) {
        String title = "test_upload_web_m3u8";
        String m3u8FileURL = "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-538087dcf2c201c31ce4324bf76af69****.m3u8";
        UploadWebM3u8Request request = new UploadWebM3u8Request(accessKeyId, accessKeySecret, title, m3u8FileURL);
        String[] sliceFileURLs = new String[]{
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts"
        };
        // Optional. The list of .ts parts. If you leave this parameter empty, ApsaraVideo VOD automatically parses the m3u8FileURL parameter to obtain the URLs of .ts parts.
        request.setSliceFileURLs(sliceFileURLs);
        /* The custom temporary directory in which downloaded files are stored. If you leave this parameter empty, the downloaded files are stored in the directory in which your application resides. */
        // request.setGlobalLocalFilePath("/User/download/");
        /* 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. Concurrent threads consume the CPU resources of the server. You can specify a value based on your server load. */
        request.setTaskNum(1);
        /* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
        //request.setShowWaterMark(true);
        /* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
        //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
        /* Optional. Specify the category ID of the video. */
        //request.setCateId(-1L);
        /* 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.example.com/sample.jpg");
        /* Optional. Specify the ID of the template group that is used for the video. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* Optional. Specify the ID of the workflow. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* Optional. Specify the storage location. */
        //request.setStorageLocation("in-2017032321****-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /* Specify the ID of the application. */
        //request.setAppId("app-100****");
        /* Specify the access region of ApsaraVideo VOD. */
        //request.setApiRegionId("cn-shanghai");
        /* Specify the region in which the ECS instance is deployed. */
        // request.setEcsRegionId("cn-shanghai");

        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. Specify the address of the proxy server. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. Specify the port that is used to connect to the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);

        UploadM3u8FileImpl uploadM3u8File = new UploadM3u8FileImpl();
        UploadWebM3u8Response uploadWebM3u8Response = uploadM3u8File.uploadWebM3u8(request);
        System.out.println("code = " + uploadWebM3u8Response.getCode());
        System.out.println("message = " + uploadWebM3u8Response.getMessage());
        System.out.println("videoId = " + uploadWebM3u8Response.getVideoId());
        System.out.println("requestId = " + uploadWebM3u8Response.getRequestId());
    }
}

Scenario 2: Upload images

Show sample code

public class UploadImageDemo {
    // Required. Enter the AccessKey pair of your Alibaba Cloud account.
    // 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 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. 
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    
    public static void main(String[] args) {
        // Upload an image.
        // Upload a local image.
         testUploadImageLocalFile(accessKeyId, accessKeySecret);
        // Use streaming upload to upload a file stream or a network stream as an image.
         testUploadImageStream(accessKeyId, accessKeySecret);
    }
    /**
     * Specify the API operation that is used to upload local images.
     *
     * @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 = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        request.setImageType("cover");
        /* Optional. Specify the file name extension of the image. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* Optional. Specify the title of the image. The title cannot exceed 128 bytes in length and must be 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 location. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* Optional. In streaming upload, the InputStream parameter is required, and the fileName parameter is optional. Set the fileName parameter to the name of the source file. The file name must contain an extension, such as .png. */
        String fileName = "/Users/demo/png/test.png";
        request.setFileName(fileName);
        /* Enable the default callback for the upload progress. */
        //request.setPrintProgress(false);
        /* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
        /* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Specify the ID of the application. */
        //request.setAppId("app-100****");
        /* Specify the access region of ApsaraVideo VOD. */
        //request.setApiRegionId("cn-shanghai");

        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. Specify the address of the proxy server. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. Specify the port that is used to connect to the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);

        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");
        }
    }
    /**
     * Specify the API operation that is used to upload a file stream or a network stream as an image.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageStream(String accessKeyId, String accessKeySecret) {
        /* Required. Specify the type of the image. Valid values: default, cover, and watermark. */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        /* Optional. Specify the file name extension of the image. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* Optional. Specify the title of the image. The title cannot exceed 128 bytes in length and must be 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 location. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* Optional. In streaming upload, the InputStream parameter is required, and the fileName parameter is optional. Set the fileName parameter to the name of the source file. The file name must contain an extension, such as .png. */
        //request.setFileName("Test file name.png");
        /* Enable the default callback for the upload progress. */
        // request.setPrintProgress(true);
        /* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
        /* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Specify the ID of the application. */
        //request.setAppId("app-1000000");

        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. Specify the address of the proxy server. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. Specify the port that is used to connect to the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        
        // Upload a file stream.
        // InputStream fileStream = getFileStream(request.getFileName());
        // if (fileStream != null) { 
        //     request.setInputStream(fileStream);
        // }
        // Upload a network stream.
        String url = "http://test.aliyun.com/image/default/test.png";
        InputStream urlStream = getUrlStream(url);
        if (urlStream != null) {
            request.setInputStream(urlStream); 
       }
        // Start the upload.
        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");
        }
    }
    private static InputStream getFileStream(String fileName) {
        try {
            return new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    private static InputStream getUrlStream(String url) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}          

Scenario 3: Upload auxiliary media assets

Show sample code

public class UploadAttachedMediaDemo {
    // Required. Enter the AccessKey pair of your Alibaba Cloud account.
    // 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 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. 
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    
    public static void main(String[] args) {
        // Upload an auxiliary media asset.
        // Upload a local auxiliary media asset.
        testUploadAttachedMediaLocalFile(accessKeyId, accessKeySecret);
        // Use streaming upload to upload a file stream or a network stream as an auxiliary media asset.
        testUploadAttachedMediaStream(accessKeyId, accessKeySecret);
    }
 /**
     * Specify the API operation that is used to upload a local auxiliary media asset.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaLocalFile(String accessKeyId, String accessKeySecret) {
        /* Specify the business type. */
        String businessType = "watermark";
        /* Specify the file name extension. */
        String mediaExt = "png";
        String filename = "/Users/demo/png/test.png";
        UploadAttachedMediaRequest request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
        request.setFileName(filename);
        /* Specify the title. */
        request.setTitle("test_attached_media");
        /* Specify the category ID. */
        request.setCateId(-1L);
        /* Optional. Specify the tags. Separate multiple tags with commas (,). */
        request.setTags("tag1,tag2");
        /* Optional. Specify the description. */
        request.setDescription("test_desc");
        /* Optional. Specify the storage location. */
        request.setStorageLocation("out-20170323225118266-5l3hs5****.oss-cn-shanghai.aliyuncs.com");
        /* Specify the access region of ApsaraVideo VOD. */
        request.setApiRegionId("cn-shanghai");
        /* Specify the ID of the application. */
        //request.setAppId("app-1000000");

        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. Specify the address of the proxy server. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. Specify the port that is used to connect to the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        
        UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();
        UploadAttachedMediaResponse response = uploader.upload(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");
        if (response.isSuccess()) {
            System.out.print("MediaId=" + response.getMediaId() + "\n");
            System.out.print("MediaURL=" + response.getMediaURL() + "\n");
            System.out.print("FileURL=" + response.getFileURL() + "\n");
        } else {
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
    }
     /**
     * Specify the API operation that is used to upload a file stream or a network stream as an auxiliary media asset.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaStream(String accessKeyId, String accessKeySecret) {
        /* Specify the business type. */

        String businessType = "watermark";

        /* Specify the file name extension. */
        String mediaExt = "png";

        String filename = "http://test.aliyun.com/test.png";

        UploadAttachedMediaRequest request;
        // Upload a file stream.

        InputStream fileStream = getFileStream(filename);

        request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
        request.setInputStream(fileStream);


        // Upload a network stream.

//        String url = "http://test.aliyun.com/image//test.png";

//        InputStream urlStream = getUrlStream(url);

//        request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
//        request.setInputStream(urlStream);

        /* Specify the title. */

        request.setTitle("test_attached_media");
        /* Specify the category ID. */
        request.setCateId(-1L);
        /* Optional. Specify the tags. Separate multiple tags with commas (,). */
        request.setTags("tag1,tag2");

        /* Optional. Specify the description. */
        request.setDescription("test_desc");

        /* Optional. Specify the storage location. */

        request.setStorageLocation("out-20170323225118266-5l3****wa.oss-cn-shanghai.aliyuncs.com");

        /* Specify the access region of ApsaraVideo VOD. */
        request.setApiRegionId("cn-shanghai");

        /* Specify the ID of the application. */

        // request.setAppId("app-1000000");

        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. Specify the address of the proxy server. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. Specify the port that is used to connect to the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);

        // Start the upload.

        UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();

        UploadAttachedMediaResponse response = uploader.upload(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");
        if (response.isSuccess()) {

            System.out.print("MediaId=" + response.getMediaId() + "\n");

            System.out.print("MediaURL=" + response.getMediaURL() + "\n");

            System.out.print("FileURL=" + response.getFileURL() + "\n");
        } else {

            System.out.print("ErrorCode=" + response.getCode() + "\n");

            System.out.print("ErrorMessage=" + response.getMessage() + "\n");

        }

    }
    private static InputStream getFileStream(String fileName) {
        try {
            return new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    private static InputStream getUrlStream(String url) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Advanced feature

  • 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 create custom business processing logic for different event notifications.

    The following sample code provides an example:

    Show sample code

    /**
     * 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 are uploaded to OSS.
         */
        private long bytesWritten = 0;
        /**
         * The total size of the source file. Unit: bytes.
         */
        private long totalBytes = -1;
        /**
         * Indicates 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 are 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 for refreshing temporary tokens

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

    Sample code:

    Show sample code

    /**
     * @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

Problem 1: The SDK may fail to find related dependencies due to the differences among development environments. In most cases, this issue is caused by compilation in the IntelliJ IDEA development environment. If you have imported the required resource packages, you can resolve the issue by using the following method:

  1. 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

  2. In the top navigation bar, choose Build > Rebuild Project to edit your project.Rebuild

  3. Copy the aliyun-java-vod-upload-1.4.15.jar package to the resource directory of the project. Add a local dependency to the Maven dependencies. The following figure shows the local dependency.问题

    <dependency>
            <groupId>com.aliyun.vod</groupId>
            <artifactId>upload</artifactId>
            <version>1.4.15</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/aliyun-java-vod-upload-1.4.15.jar</systemPath>
    </dependency>

    Sample Maven dependencies after the local dependency is added:

       <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.16.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68.noneautotype</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>
        <dependency>
            <groupId>com.aliyun.vod</groupId>
            <artifactId>upload</artifactId>
            <version>1.4.15</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/aliyun-java-vod-upload-1.4.15.jar</systemPath>
        </dependency>

References

Overview

STS SDK overview

Demo