All Products
Search
Document Center

ApsaraVideo VOD:Use the upload SDK for Java

Last Updated:Nov 17, 2025

This topic provides examples of how to use the server-side upload SDK for Java to upload various media files to ApsaraVideo VOD storage.

Overview

The upload SDK for Java follows the same general process as other ApsaraVideo VOD server-side SDKs. For more information, see Upload process. The basic steps to use the upload SDK for Java are as follows:

  1. Complete the prerequisites. 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. This step mainly involves 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.

  • Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.

    Important
    • The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use the AccessKey pair of a RAM user to call API operations or perform routine O&M.

    • We recommend that you do not hard-code the AccessKey ID and AccessKey secret into your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account is compromised.

  • Optional. A role is created for the RAM user and the role is granted the permissions required to access ApsaraVideo VOD if you want to access ApsaraVideo VOD by using Security Token Service (STS). For more information, see Obtain an STS token.

    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

This topic uses Java 1.8 or later and the upload SDK for Java V1.4.15 to describe the integration steps. You can use other versions as needed. The upload SDK does not support dependency integration. You must download and import the JAR package. If you encounter problems during integration, see FAQ.

  1. Download the upload SDK for Java and the sample code.

  2. Decompress the downloaded package.

    The VODUploadDemo-java-1.4.15.zip package is used in this example. After you decompress the package, the following subfolders are created:

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

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

  3. Import the JAR packages.

    • If you are integrating with Eclipse, right-click your project and choose Properties > Java Build Path > Add JARs. Find the decompressed VODUploadDemo-java-1.4.15 folder and add all JAR files from the lib directory to your project.

    • To integrate with IntelliJ IDEA, open your project and choose File > Project Structure > Modules. On the Dependencies tab, click the + icon and select JARs or directories. Find the decompressed VODUploadDemo-java-1.4.15 folder and add all JAR files from the lib directory to your project.

    Important

    After you import the JAR packages, you must also configure dependencies.

  4. You can add dependencies, such as the Alibaba Cloud SDK for Java, the OSS SDK, the ApsaraVideo VOD SDK, and the ApsaraVideo VOD server-side upload SDK.

    Important
    • You must import all the preceding dependencies. Otherwise, the integration will fail.

    • If you use the latest JAR package (aliyun-java-vod-upload-1.4.15.jar), make sure that the version of aliyun-sdk-oss is 3.9.0 or later and the version of aliyun-java-sdk-vod is 2.16.11 or later.

    • ApsaraVideo VOD is available in the China (Shanghai), China (Shenzhen), and China (Beijing) regions in the Chinese mainland. If you use the upload SDK V1.4.14 or earlier to upload files to the China (Shenzhen) or China (Beijing) region, make sure that the version of aliyun-java-sdk-vod is 2.15.11 or later and the version of aliyun-java-sdk-core is 4.4.5 or later. If you use the upload SDK V1.4.15 or later to upload files to the China (Shenzhen) or China (Beijing) region, make sure that the version of aliyun-java-sdk-vod is 2.16.11 or later and the version of aliyun-java-sdk-core is 4.4.5 or later.

    Expand to view 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.83</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 and video files

Regular audio and video files

You can upload audio and video files in one of the following ways:

  • Upload a local file. This method uses multipart upload and supports resumable upload. For more information, see the testUploadVideo function in the sample code.

    • If resumable upload is disabled, an upload task can run for a maximum of 3,000 seconds. The maximum size of a file that can be uploaded depends on your network bandwidth and disk I/O performance.

    • If resumable upload is enabled, you can upload a single file of up to 48.8 TB.

      Important

      If you enable resumable upload, the upload progress is written to a local disk file during the upload. This may affect the upload speed. We recommend that you decide whether to enable this feature based on the file size.

  • Upload a network stream. You can specify a file URL to upload a file. This method supports resumable upload and lets you upload a single file of up to 48.8 TB. This method requires the network file to be downloaded to a local disk before it is uploaded. Make sure that your local disk has sufficient space. For more information, see the testUploadURLStream function in the sample code.

  • Upload a file stream. You can specify a local file to upload. This method does not support resumable upload and lets you upload a single file of up to 5 GB. For more information, see the testUploadFileStream function in the sample code.

  • Use streaming upload. You can specify an input stream to upload, such as a file stream or a network stream. This method does not support resumable upload and lets you upload a single file of up to 5 GB. For more information, see the testUploadStream function in the sample code.

Important

When you use the sample code, you must manually import the corresponding classes. To resolve issues, such as a dependency not being found during code execution, see FAQ.

Expand to view sample code

public class UploadVideoDemo {
    // Required. Specify the AccessKey pair.
    // The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. We recommend that you use the AccessKey pair of a RAM user for API calls or routine O&M.
    // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account is compromised.
    // This example shows how to read the AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    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.
    // The video title. This parameter is required.
    String title = "Test Title";
    // 1. For local file upload and file stream upload, set the file name to the absolute path of the upload file, such as /User/sample/FileName.mp4. This parameter is required.
    // 2. For network stream upload, set the file name to the source file name, such as FileName.mp4. This parameter is required.
    // 3. For streaming upload, set the file name to the source file name, such as FileName.mp4. This parameter is required.
    // The file name must include the file name extension regardless of the upload method.
    String fileName = "/Users/test/video/test.mp4";
    // Upload a local file.
    testUploadVideo(accessKeyId, accessKeySecret, title, fileName);

    // The URL of the network stream for the video to be uploaded.
    String url = "http://test.aliyun.com/video/test.mp4";

    // 2. Upload a network stream.
    // The file name extension. If the URL does not contain the file name extension, you must set this parameter.
    String fileExtension = "mp4";
    testUploadURLStream(accessKeyId, accessKeySecret, title, url, fileExtension);

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

    // 4. Streaming upload, such as file stream and network stream.
    InputStream inputStream = null;
    // 4.1 File stream.
    try {
        inputStream = new FileInputStream(fileName);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // 4.2 Network stream.
    try {
        inputStream = new URL(url).openStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    testUploadStream(accessKeyId, accessKeySecret, title, fileName, inputStream);
}

/**
 * The API for local file upload.
 *
 * @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);
    /* The size of each part for multipart upload. Default value: 2 MB. */
    request.setPartSize(2 * 1024 * 1024L);
    /* The number of concurrent threads for multipart upload. Default value: 1. Note: This configuration consumes CPU resources of the server. Specify the number of threads based on your server performance. */
    request.setTaskNum(1);
    /* Specifies whether to enable resumable upload. Default value: false. If the network is unstable or the program crashes, you can resume the upload task by sending the same upload request. This feature is suitable for large files that cannot be uploaded within 3,000 seconds.
    Note: If you enable resumable upload, the upload progress is written to a local disk file during the upload. This affects the upload speed. Choose whether to enable this feature as needed. */
    //request.setEnableCheckpoint(false);
    /* The timeout period for logging slow OSS requests. If the time to upload a part exceeds this threshold, a debug log is printed. To suppress this log, adjust the threshold. Unit: milliseconds. Default value: 300000. */
    //request.setSlowRequestsThreshold(300000L);
    /* The time threshold for logging a slow request for each part. Default value: 300s. */
    //request.setSlowRequestsThreshold(300000L);
    /* Specifies whether to display the watermark. This parameter is optional. If you specify a template group ID, the watermark is displayed based on the template group configuration. */
    //request.setIsShowWaterMark(true);
    /* Custom message callback settings and upload acceleration settings. This parameter is optional. Extend specifies custom extension settings. MessageCallback specifies message callback settings. AccelerateConfig specifies upload acceleration settings. You must activate the upload acceleration feature before you can use it. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
    /* The video category ID. This parameter is optional. */
    //request.setCateId(0);
    /* The video tags. Separate multiple tags with commas (,). This parameter is optional. */
    //request.setTags("Tag 1,Tag 2");
    /* The video description. This parameter is optional. */
    //request.setDescription("Video description");
    /* The thumbnail URL. This parameter is optional. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* The template group ID. This parameter is optional. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e5****");
    /* The workflow ID. This parameter is optional. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* The storage region. This parameter is optional. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enables the default upload progress callback. */
    //request.setPrintProgress(false);
    /* Sets a custom upload progress callback. The callback must inherit VoDProgressListener. */
    /* This feature is disabled by default. If you enable this feature, the server returns upload details in the log during the upload. If you do not need to receive this message, disable this feature. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* Sets the implementation class of the interface that you use to generate STS information. */
    // request.setVoDRefreshSTSTokenListener(new RefreshSTSTokenImpl());
    /* Sets the application ID. */
    //request.setAppId("app-100****");
    /* The ApsaraVideo VOD endpoint. */
    //request.setApiRegionId("cn-shanghai");
    /* The ECS deployment region. */
    // request.setEcsRegionId("cn-shanghai");
    // If the ECS deployment region is the same as the ApsaraVideo VOD endpoint region, internal network upload is automatically enabled.

    /* Configures a proxy. This parameter is optional. */
    //OSSConfig ossConfig = new OSSConfig();
    /* <Required> The proxy server host. */
    //ossConfig.setProxyHost("<yourProxyHost>");
    /* <Required> The proxy server port. */
    //ossConfig.setProxyPort(-1);
    /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
    //ossConfig.setProtocol("HTTP");
    /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
    //ossConfig.setUserAgent("<yourUserAgent>");
    /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
    //ossConfig.setProxyUsername("<yourProxyUserName>");
    /* The password for proxy server authentication. This parameter is required for 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");  // The ID of the request sent to ApsaraVideo VOD.
    if (response.isSuccess()) {
        System.out.print("VideoId=" + response.getVideoId() + "\n");
    } else {
        /* If the specified callback URL is invalid, the video upload is not affected. A VideoId and an error code are returned. In other cases, if the upload fails, the VideoId is empty. In this case, analyze the cause of the failure 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");
    }
}

/**
 * Uploads a network stream using a URL. This method supports resumable upload. You can upload a single file of up to 48.8 TB.
 * This method requires the network file to be downloaded to a local disk before it is uploaded. Make sure that your local disk has sufficient space.
 * If the URL that you specify does not include a file name extension, you must set 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);

    /* The file name extension. */
    request.setFileExtension(fileExtension);
    /* The connection timeout period for downloading the network file. Unit: milliseconds. A value of 0 indicates no limit. */
    request.setDownloadConnectTimeout(1000);
    /* The read timeout period for downloading the network file. Unit: milliseconds. A value of 0 indicates no limit. */
    request.setDownloadReadTimeout(0);
    /* The local directory where the downloaded network file is saved. */
    request.setLocalDownloadFilePath("/Users/download");
    /* Specifies whether to display the watermark. This parameter is optional. If you specify a template group ID, the watermark is displayed based on the template group configuration. */
    //request.setShowWaterMark(true);
    /* Custom message callback settings and upload acceleration settings. This parameter is optional. Extend specifies custom extension settings. MessageCallback specifies message callback settings. AccelerateConfig specifies upload acceleration settings. You must activate the upload acceleration feature before you can use it. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
    /* The video category ID. This parameter is optional. */
    //request.setCateId(0);
    /* The video tags. Separate multiple tags with commas (,). This parameter is optional. */
    //request.setTags("Tag 1,Tag 2");
    /* The video description. This parameter is optional. */
    //request.setDescription("Video description");
    /* The thumbnail URL. This parameter is optional. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* The template group ID. This parameter is optional. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* The workflow ID. This parameter is optional. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* The storage region. This parameter is optional. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enables the default upload progress callback. */
    //request.setPrintProgress(true);
    /* Sets a custom upload progress callback. The callback must inherit VoDProgressListener. */
    /* This feature is disabled by default. If you enable this feature, the server returns upload details in the log during the upload. If you do not need to receive this message, disable this feature. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* Sets the application ID. */
    //request.setAppId("app-100****");
    /* The ApsaraVideo VOD endpoint. */
    //request.setApiRegionId("cn-shanghai");
    /* The ECS deployment region. */
    // request.setEcsRegionId("cn-shanghai");
    // If the ECS deployment region is the same as the ApsaraVideo VOD endpoint region, internal network upload is automatically enabled.

     /* Configures a proxy. This parameter is optional. */
     //OSSConfig ossConfig = new OSSConfig();
     /* <Required> The proxy server host. */
     //ossConfig.setProxyHost("<yourProxyHost>");
     /* <Required> The proxy server port. */
     //ossConfig.setProxyPort(-1);
     /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
     //ossConfig.setProtocol("HTTP");
     /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("<yourUserAgent>");
     /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
     //ossConfig.setProxyUsername("<yourProxyUserName>");
     /* The password for proxy server authentication. This parameter is required for 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"); // The ID of the request sent to ApsaraVideo VOD.
    if (response.isSuccess()) {
        System.out.print("VideoId=" + response.getVideoId() + "\n");
    } else {
        /* If the specified callback URL is invalid, the video upload is not affected. A VideoId and an error code are returned. In other cases, if the upload fails, the VideoId is empty. In this case, analyze the cause of the failure 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");
    }
}

/**
 * The API for file stream upload.
 *
 * @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);
    /* Specifies whether to use the default watermark. This parameter is optional. If you specify a template group ID, the default watermark is used based on the template group configuration. */
    //request.setShowWaterMark(true);
    /* Custom message callback settings and upload acceleration settings. This parameter is optional. Extend specifies custom extension settings. MessageCallback specifies message callback settings. AccelerateConfig specifies upload acceleration settings. You must activate the upload acceleration feature before you can use it. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
    /* The video category ID. This parameter is optional. */
    //request.setCateId(0);
    /* The video tags. Separate multiple tags with commas (,). This parameter is optional. */
    //request.setTags("Tag 1,Tag 2");
    /* The video description. This parameter is optional. */
    //request.setDescription("Video description");
    /* The thumbnail URL. This parameter is optional. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* The template group ID. This parameter is optional. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* The workflow ID. This parameter is optional. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* The storage region. This parameter is optional. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enables the default upload progress callback. */
    //request.setPrintProgress(true);
    /* Sets a custom upload progress callback. The callback must inherit VoDProgressListener. */
    /* This feature is disabled by default. If you enable this feature, the server returns upload details in the log during the upload. If you do not need to receive this message, disable this feature. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* Sets the application ID. */
    //request.setAppId("app-100****");
    /* The ApsaraVideo VOD endpoint. */
    //request.setApiRegionId("cn-shanghai");
    /* The ECS deployment region. */
    // request.setEcsRegionId("cn-shanghai");
    // If the ECS deployment region is the same as the ApsaraVideo VOD endpoint region, internal network upload is automatically enabled.

     /* Configures a proxy. This parameter is optional. */
     //OSSConfig ossConfig = new OSSConfig();
     /* <Required> The proxy server host. */
     //ossConfig.setProxyHost("<yourProxyHost>");
     /* <Required> The proxy server port. */
     //ossConfig.setProxyPort(-1);
     /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
     //ossConfig.setProtocol("HTTP");
     /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("<yourUserAgent>");
     /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
     //ossConfig.setProxyUsername("<yourProxyUserName>");
     /* The password for proxy server authentication. This parameter is required for 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"); // The ID of the request sent to ApsaraVideo VOD.
    if (response.isSuccess()) {
        System.out.print("VideoId=" + response.getVideoId() + "\n");
    } else {
        /* If the specified callback URL is invalid, the video upload is not affected. A VideoId and an error code are returned. In other cases, if the upload fails, the VideoId is empty. In this case, analyze the cause of the failure 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");
    }
}

/**
 * The API 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);
     /* Specifies whether to use the default watermark. This parameter is optional. If you specify a template group ID, the default watermark is used based on the template group configuration. */
    //request.setShowWaterMark(true);
    /* Custom message callback settings and upload acceleration settings. This parameter is optional. Extend specifies custom extension settings. MessageCallback specifies message callback settings. AccelerateConfig specifies upload acceleration settings. You must activate the upload acceleration feature before you can use it. */
    //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
    /* The video category ID. This parameter is optional. */
    //request.setCateId(0);
    /* The video tags. Separate multiple tags with commas (,). This parameter is optional. */
    //request.setTags("Tag 1,Tag 2");
    /* The video description. This parameter is optional. */
    //request.setDescription("Video description");
    /* The thumbnail URL. This parameter is optional. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* The template group ID. This parameter is optional. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* The workflow ID. This parameter is optional. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* The storage region. This parameter is optional. */
    //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
    /* Enables the default upload progress callback. */
    // request.setPrintProgress(true);
    /* Sets a custom upload progress callback. The callback must inherit VoDProgressListener. */
    /* This feature is disabled by default. If you enable this feature, the server returns upload details in the log during the upload. If you do not need to receive this message, disable this feature. */
    // request.setProgressListener(new PutObjectProgressListener());
     /* Sets the application ID. */
    //request.setAppId("app-100****");
    /* The ApsaraVideo VOD endpoint. */
    //request.setApiRegionId("cn-shanghai");
    /* The ECS deployment region. */
    // request.setEcsRegionId("cn-shanghai");
    // If the ECS deployment region is the same as the ApsaraVideo VOD endpoint region, internal network upload is automatically enabled.

     /* Configures a proxy. This parameter is optional. */
     //OSSConfig ossConfig = new OSSConfig();
     /* <Required> The proxy server host. */
     //ossConfig.setProxyHost("<yourProxyHost>");
     /* <Required> The proxy server port. */
     //ossConfig.setProxyPort(-1);
     /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
     //ossConfig.setProtocol("HTTP");
     /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("<yourUserAgent>");
     /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
     //ossConfig.setProxyUsername("<yourProxyUserName>");
     /* The password for proxy server authentication. This parameter is required for 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");  // The ID of the request sent to ApsaraVideo VOD.
    if (response.isSuccess()) {
        System.out.print("VideoId=" + response.getVideoId() + "\n");
    } else { // If the specified callback URL is invalid, the video upload is not affected. A VideoId and an error code are returned. In other cases, if the upload fails, the VideoId is empty. In this case, analyze the cause of the failure 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

Expand to view sample code

public class UploadVideoDemo {
    // Required. Specify the AccessKey pair.
    // The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. We recommend that you use the AccessKey pair of a RAM user for API calls or routine O&M.
    // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account is compromised.
    // This example shows how to read the AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    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.
        // 1. Upload a local M3U8 audio or video file.
        testUploadLocalM3u8(accessKeyId, accessKeySecret);
        // 2. Upload a web-based M3U8 audio or video file.
        testUploadWebM3u8(accessKeyId, accessKeySecret);
    }
    /**
     * Uploads a local M3U8 video or audio file to ApsaraVideo VOD. By default, the M3U8 file and its shards are in the same directory. If sliceFilenames is empty, the shard addresses are parsed from the same directory.
     *
     * @param request The request to upload a local M3U8 file.
     *                m3u8Filename: The absolute path of the local M3U8 manifest. The shard information in the M3U8 file must be a relative path. It cannot contain a URL or an absolute local path.
     *                sliceFilenames: A list of absolute paths of the TS shards. If you specify this parameter, this list is used. If you do not specify this parameter, the m3u8 file specified by m3u8Filename is automatically parsed.
     */
    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"
        };
        // A list of TS shard files. This parameter is optional. If you do not specify this parameter, the shard addresses are parsed directly from the M3U8 file.
        request.setSliceFilenames(sliceFilenames);
        /* The size of each part for multipart upload. Default value: 2 MB. */
        request.setPartSize(2 * 1024 * 1024L);
        /* The number of concurrent threads for multipart upload. Default value: 1. Note: This configuration consumes CPU resources of the server. Specify the number of threads based on your server performance. */
        request.setTaskNum(1);
        /* Specifies whether to display the watermark. This parameter is optional. If you specify a template group ID, the watermark is displayed based on the template group configuration. */
        //request.setShowWaterMark(true);
        /* Custom message callback settings and upload acceleration settings. This parameter is optional. Extend specifies custom extension settings. MessageCallback specifies message callback settings. AccelerateConfig specifies upload acceleration settings. You must activate the upload acceleration feature before you can use it. */
        //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
        /* The video category ID. This parameter is optional. */
        //request.setCateId(-1L);
        /* The video tags. Separate multiple tags with commas (,). This parameter is optional. */
        //request.setTags("Tag 1,Tag 2");
        /* The video description. This parameter is optional. */
        //request.setDescription("Video description");
        /* The thumbnail URL. This parameter is optional. */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* The template group ID. This parameter is optional. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* The workflow ID. This parameter is optional. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* The storage region. This parameter is optional. */
        //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
        /* Sets the application ID. */
        // request.setAppId("app-1000000");
        /* The ApsaraVideo VOD endpoint. */
        // request.setApiRegionId("cn-shanghai");
        /* The ECS deployment region. */
        // request.setEcsRegionId("cn-shanghai");

        /* Configures a proxy. This parameter is optional. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required for 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());
    }

    /**
     * Uploads a web-based M3U8 video or audio file to ApsaraVideo VOD. Sufficient local disk space is required because the file is first downloaded to a temporary local directory and then uploaded to ApsaraVideo VOD storage.
     *
     * @param request The request to upload a web-based M3U8 file.
     *                m3u8FileURL: The URL of the web-based M3U8 manifest. The shard information in the M3U8 file must be a relative path. It cannot contain a URL or an absolute local path.
     *                sliceFileURLs: A list of URLs of the TS shards. You must construct the list of TS shard URLs yourself.
     */
    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"
        };
        // The TS shard addresses. This parameter is optional. If you do not specify this parameter, the shard addresses are parsed directly from m3u8FileURL.
        request.setSliceFileURLs(sliceFileURLs);
        /* The temporary storage directory for downloaded files. You can customize this directory. If you do not specify a directory, the files are saved to the directory where the program runs. */
        // request.setGlobalLocalFilePath("/User/download/");
        /* The size of each part for multipart upload. Default value: 2 MB. */
        request.setPartSize(2 * 1024 * 1024L);
        /* The number of concurrent threads for multipart upload. Default value: 1. Note: This configuration consumes CPU resources of the server. Specify the number of threads based on your server performance. */
        request.setTaskNum(1);
        /* Specifies whether to display the watermark. This parameter is optional. If you specify a template group ID, the watermark is displayed based on the template group configuration. */
        //request.setShowWaterMark(true);
        /* Custom message callback settings and upload acceleration settings. This parameter is optional. Extend specifies custom extension settings. MessageCallback specifies message callback settings. AccelerateConfig specifies upload acceleration settings. You must activate the upload acceleration feature before you can use it. */
        //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
        /* The video category ID. This parameter is optional. */
        //request.setCateId(-1L);
        /* The video tags. Separate multiple tags with commas (,). This parameter is optional. */
        //request.setTags("Tag 1,Tag 2");
        /* The video description. This parameter is optional. */
        //request.setDescription("Video description");
        /* The thumbnail URL. This parameter is optional. */
        //request.setCoverURL("http://cover.example.com/sample.jpg");
        /* The template group ID. This parameter is optional. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* The workflow ID. This parameter is optional. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* The storage region. This parameter is optional. */
        //request.setStorageLocation("in-2017032321****-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /* Sets the application ID. */
        //request.setAppId("app-100****");
        /* The ApsaraVideo VOD endpoint. */
        //request.setApiRegionId("cn-shanghai");
        /* The ECS deployment region. */
        // request.setEcsRegionId("cn-shanghai");

        /* Configures a proxy. This parameter is optional. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required for 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());
    }
}

Upload acceleration

If you want to upload large files that are gigabytes or terabytes in size, or upload videos across regions, such as from the Chinese mainland to a storage address in the Singapore region, you can enable the upload acceleration feature. For more information, see Enable upload acceleration. After you enable upload acceleration, you must add the corresponding key-value pair AccelerateConfig to the UserData object in the upload configuration. If the object does not exist, you must create one. The following code provides an example:

request.setUserData("{\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");

Parameter descriptions

Name

Type

Description

Type

string

The type for which you want to enable upload acceleration. Only oss is supported.

Domain

string

The accelerated domain name of the bucket. The default protocol is HTTPS.

Note

Use an accelerated endpoint that is assigned after you enable upload acceleration, such as vod-*******.oss-accelerate.aliyuncs.com.

Scenario 2: Upload images

Expand to view sample code

public class UploadImageDemo {
    // Required. Specify the AccessKey pair.
    // The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. We recommend that you use the AccessKey pair of a RAM user for API calls or routine O&M.
    // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account is compromised.
    // This example shows how to read the AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    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.
        // 1. Upload a local image file.
         testUploadImageLocalFile(accessKeyId, accessKeySecret);
        // 2. Use streaming upload to upload a file stream or a network stream as an image.
         testUploadImageStream(accessKeyId, accessKeySecret);
    }
    /**
     * The API for local image file upload.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageLocalFile(String accessKeyId, String accessKeySecret) {
        /* The image type. This parameter is required. Valid values: default, cover, and watermark. */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        request.setImageType("cover");
        /* The file name extension of the image. This parameter is optional. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* The image title. This parameter is optional. The title can be up to 128 bytes in length and must be UTF-8 encoded. */
        //request.setTitle("Image Title");
        /* The image tags. This parameter is optional. A single tag can be up to 32 bytes in length. You can add up to 16 tags. Separate multiple tags with commas (,). The tags must be UTF-8 encoded. */
        //request.setTags("Tag 1,Tag 2");
        /* The storage region. This parameter is optional. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* For streaming upload, InputStream is required, and fileName is optional. fileName specifies the source file name, such as FileName.png. */
        String fileName = "/Users/demo/png/test.png";
        request.setFileName(fileName);
        /* Enables the default upload progress callback. */
        //request.setPrintProgress(false);
        /* Sets a custom upload progress callback. The callback must inherit VoDProgressListener. */
        /* This feature is disabled by default. If you enable this feature, the server returns upload details in the log during the upload. If you do not need to receive this message, disable this feature. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Sets the application ID. */
        //request.setAppId("app-100****");
        /* The ApsaraVideo VOD endpoint. */
        //request.setApiRegionId("cn-shanghai");

        /* Configures a proxy. This parameter is optional. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required for 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");
        }
    }
    /**
     * The API for streaming upload of images. This method supports file streams and network streams.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageStream(String accessKeyId, String accessKeySecret) {
        /* The image type. This parameter is required. Valid values: default, cover, and watermark. */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        /* The file name extension of the image. This parameter is optional. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* The image title. This parameter is optional. The title can be up to 128 bytes in length and must be UTF-8 encoded. */
        //request.setTitle("Image Title");
        /* The image tags. This parameter is optional. A single tag can be up to 32 bytes in length. You can add up to 16 tags. Separate multiple tags with commas (,). The tags must be UTF-8 encoded. */
        //request.setTags("Tag 1,Tag 2");
        /* The storage region. This parameter is optional. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* For streaming upload, InputStream is required, and fileName is optional. fileName specifies the source file name, such as FileName.png. */
        //request.setFileName("TestFileName.png");
        /* Enables the default upload progress callback. */
        // request.setPrintProgress(true);
        /* Sets a custom upload progress callback. The callback must inherit VoDProgressListener. */
        /* This feature is disabled by default. If you enable this feature, the server returns upload details in the log during the upload. If you do not need to receive this message, disable this feature. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Sets the application ID. */
        //request.setAppId("app-1000000");

        /* Configures a proxy. This parameter is optional. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required for the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        
        // 1. Upload a file stream.
        // InputStream fileStream = getFileStream(request.getFileName());
        // if (fileStream != null) { 
        //     request.setInputStream(fileStream);
        // }
        // 2. 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 uploading the image.
        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

Expand to view sample code

public class UploadAttachedMediaDemo {
    // Required. Specify the AccessKey pair.
    // The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. We recommend that you use the AccessKey pair of a RAM user for API calls or routine O&M.
    // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account is compromised.
    // This example shows how to read the AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    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 file.
        testUploadAttachedMediaLocalFile(accessKeyId, accessKeySecret);
        // Use streaming upload to upload an auxiliary media asset. This method supports file streams and network streams.
        testUploadAttachedMediaStream(accessKeyId, accessKeySecret);
    }
 /**
     * The API for local auxiliary media asset file upload.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaLocalFile(String accessKeyId, String accessKeySecret) {
        /* The business type. */
        String businessType = "watermark";
        /* 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);
        /* The title. */
        request.setTitle("test_attached_media");
        /* The category ID. */
        request.setCateId(-1L);
        /* The tags. Separate multiple tags with commas (,). This parameter is optional. */
        request.setTags("tag1,tag2");
        /* The description. This parameter is optional. */
        request.setDescription("test_desc");
        /* The storage region. This parameter is optional. */
        request.setStorageLocation("out-20170323225118266-5l3hs5****.oss-cn-shanghai.aliyuncs.com");
        /* The ApsaraVideo VOD endpoint. */
        request.setApiRegionId("cn-shanghai");
        /* Sets the application ID. */
        //request.setAppId("app-1000000");

        /* Configures a proxy. This parameter is optional. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required for 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");
        }
    }
     /**
     * The API for streaming upload of auxiliary media assets. This method supports file streams and network streams.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaStream(String accessKeyId, String accessKeySecret) {
        /* The business type. */

        String businessType = "watermark";

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

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

        UploadAttachedMediaRequest request;
        // 1. Upload a file stream.

        InputStream fileStream = getFileStream(filename);

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


        // 2. 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);

        /* The title. */

        request.setTitle("test_attached_media");
        /* The category ID. */
        request.setCateId(-1L);
        /* The tags. Separate multiple tags with commas (,). This parameter is optional. */
        request.setTags("tag1,tag2");

        /* The description. This parameter is optional. */
        request.setDescription("test_desc");

        /* The storage region. This parameter is optional. */

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

        /* The ApsaraVideo VOD endpoint. */
        request.setApiRegionId("cn-shanghai");

        /* Sets the application ID. */

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

        /* Configures a proxy. This parameter is optional. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required for the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required for 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 Features

  • Upload progress bar

    The PutObjectProgressListener.java file in the sample directory provides sample code for an upload progress callback function.

    This class must inherit the VoDProgressListener class. A ProgressEvent is a progress callback notification that is generated when a file is uploaded to OSS. You can customize the business logic for each event notification.

    The following code provides an example:

    Expand to view sample code

    /**
     * The class for the upload progress callback method.
     * This event callback takes effect only after you enable the upload progress callback.
     * The corresponding callback event is triggered regardless of whether the multipart upload to OSS succeeds or fails. You can handle the event callbacks based on your business logic.
     * After the audio or video information is created, the videoId in this upload progress callback is the ID of the video generated for this upload. You can manage audio and video files based on the video ID.
     * After the image information is created, the ImageId in this upload progress callback is the ID of the image generated for this upload. You can manage images based on the image ID.
     */
    
    public class PutObjectProgressListener implements VoDProgressListener {
        /**
         * The number of bytes that have been successfully uploaded to OSS.
         */
        private long bytesWritten = 0;
        /**
         * The total number of bytes of the source file.
         */
        private long totalBytes = -1;
        /**
         * The success flag for this upload.
         */
        private boolean succeed = false;
        /**
         * The video ID.
         */
        private String videoId;
        /**
         * The image ID.
         */
        private String imageId;
    
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
                // The upload start event.
                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 that notifies the total size of the file to be uploaded. This event is supported only for local file uploads.
                case REQUEST_CONTENT_LENGTH_EVENT:
                    this.totalBytes = bytes;
                    System.out.println(this.totalBytes + "bytes in total will be uploaded to OSS.");
                    break;
                // The event that notifies the size of the file that has been uploaded.
                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 that notifies that the file is successfully 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 that notifies that the file upload failed.
                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;
        }
    }
                        
  • Refresh a temporary token

    The RefreshSTSTokenImpl.java file in the sample directory provides sample code for refreshing a temporary token.

    The following is an example.

    Expand to view sample code

    /**
     * @author vod
     * The implementation class for generating 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

Why do I fail to find related dependencies? This issue may occur due to different development environments and is usually caused by a compilation problem in IntelliJ IDEA. If you have imported the required resource packages, try the following solutions.

  1. In your Maven project, click Maven on the right, click the m icon, and then enter mvn idea:module to reload the resources.module

  2. In the menu bar, choose Build > Rebuild Project to rebuild your project.Rebuild

  3. Copy the aliyun-java-vod-upload-1.4.15.jar package to the resource directory of your project and add it as a local dependency to your Maven dependencies.问题

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

    The following code shows an example of the 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>