Upload files with the Java SDK

Updated at:
Copy as MD

Use the server-side upload SDK for Java to upload audio, video, image, and auxiliary media files to ApsaraVideo VOD.

Overview

The Java upload SDK follows the ApsaraVideo VOD upload process. The basic steps are:

  1. Complete the Prerequisites.

  2. Integrate the Java upload SDK.

  3. Implement the upload logic (primarily upload configuration).

Prerequisites

  • ApsaraVideo VOD is activated. For more information, see Activate ApsaraVideo VOD.

  • The system settings required for the upload, including the storage path in the specified region and the callback settings, are configured. For more information, see Manage storage buckets and Configure callbacks.

  • A RAM user is created and used to access ApsaraVideo VOD. To prevent security risks caused by the leakage of the AccessKey pair of your Alibaba Cloud account, we recommend that you create a RAM user and grant the RAM user the permissions required to access ApsaraVideo VOD. Then, you can use the AccessKey pair of the RAM user to access ApsaraVideo VOD. For more information, see Create a RAM user and grant permissions.

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

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

Integrate the upload SDK for Java

Note

This example uses Java 1.8+ and upload SDK for Java 1.4.15. Steps may vary by version. The SDK requires manual JAR import — direct dependency integration is not supported. Troubleshooting.

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

  2. Decompress the downloaded package.

    After extracting VODUploadDemo-java-1.4.15.zip, you get the following folders:

    • lib: JAR packages required by the upload SDK.

    • sample: Sample code for the upload SDK.

  3. Import the JAR packages.

    • Eclipse: Right-click your project, select Properties > Java Build Path > Add JARs, navigate to the extracted VODUploadDemo-java-1.4.15 folder, and add all jar files from the lib directory.

    • IntelliJ IDEA: Select File > Project Structure > Modules, click Dependencies on the right, click +, then JARs or directories. Navigate to the extracted VODUploadDemo-java-1.4.15 directory and add all jar files from the lib directory.

    Important

    After importing the JAR packages, configure the dependencies.

  4. Add dependencies: Alibaba Cloud SDK for Java, OSS SDK, ApsaraVideo VOD server-side SDK, and ApsaraVideo VOD upload SDK.

    Important
    • All listed dependencies are required. Missing any causes integration failure.

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

    • ApsaraVideo VOD is available in the China (Shanghai), China (Shenzhen), and China (Beijing) regions. For uploads to China (Shenzhen) or China (Beijing): upload SDK 1.4.14 or earlier requires aliyun-java-sdk-vod 2.15.11+ and aliyun-java-sdk-core 4.4.5+; upload SDK 1.4.15 or later requires aliyun-java-sdk-vod 2.16.11+ and aliyun-java-sdk-core 4.4.5+.

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

ApsaraVideo VOD provides four methods for uploading audio and video files:

  • Upload a local file. Uses multipart upload with resumable upload support. Sample: testUploadVideo.

    • Without resumable upload, tasks run for a maximum of 3,000 seconds. Maximum file size depends on network bandwidth and disk I/O.

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

      Important

      Resumable upload writes progress to a local file, which may affect upload speed. Consider enabling this feature for large files.

  • Upload a network stream by URL. Supports resumable upload for files up to 48.8 TB. Downloads the file locally before uploading — ensure sufficient disk space. Sample: testUploadURLStream.

  • Upload a file stream from a local file. No resumable upload. Maximum file size: 5 GB. Sample: testUploadFileStream.

  • Upload an input stream (file stream or network stream). No resumable upload. Maximum file size: 5 GB. Sample: testUploadStream.

Important

When using the sample code, manually import the required classes. If you encounter missing dependency errors, check the FAQ.

Sample code

public class UploadVideoDemo {
    // Required: Specify your AccessKey pair.
    // An AccessKey pair from an Alibaba Cloud account can access all APIs. We recommend that you use a RAM user for API access or routine O&M.
    // Do not hard-code the AccessKey ID and AccessKey Secret in your project. Otherwise, the AccessKey pair may be leaked and all the resources in your account may be exposed to risks.
    // In this example, the AccessKey pair is obtained from environment variables. 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.
    // Required. The title of the video.
    String title = "Test Title";
    // 1. For local file upload and file stream upload, set fileName to the absolute path of the file to upload. Example: /User/sample/FileName.mp4. (Required)
    // 2. For network stream upload, set fileName to the source file name. Example: FileName.mp4. (Required)
    // 3. For streaming upload, set fileName to the source file name. Example: FileName.mp4. (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 to upload.
    String url = "http://test.aliyun.com/video/test.mp4";
    // 2. Upload a network stream.
    // The file name extension. This parameter is required if the URL does not contain the file name extension.
    String fileExtension = "mp4";
    testUploadURLStream(accessKeyId, accessKeySecret, title, url, fileExtension);
    // 3. Upload a file stream.
    testUploadFileStream(accessKeyId, accessKeySecret, title, fileName);
    // 4. Perform a streaming upload of a file stream or a 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);
}
/**
 * Upload a local file.
 *
 * @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 part size for multipart upload. Default value: 2 MB. */
    request.setPartSize(2 * 1024 * 1024L);
    /* The number of concurrent threads for multipart upload. Default value: 1. This parameter affects CPU consumption. Set this value based on your server's configuration. */
    request.setTaskNum(1);
    /* Specifies whether to enable resumable upload. By default, resumable upload is disabled. If the network is unstable or the program crashes, you can resume the upload from the point of interruption by resending the same upload request. Use this feature for large files that take longer than 3,000 seconds to upload.
    Note: If you enable resumable upload, the upload progress is written to a local file. This may affect the upload speed. You can determine whether to enable this feature based on your requirements. */
    //request.setEnableCheckpoint(false);
    /* The time threshold for logging slow OSS requests. If the time to upload a part exceeds this threshold, the system prints a debug log. To prevent these logs from being printed, increase the threshold. Unit: milliseconds. Default value: 300000. */
    //request.setSlowRequestsThreshold(300000L);
    /* The time threshold for logging slow requests for each part. Default value: 300s. */
    //request.setSlowRequestsThreshold(300000L);
    /* Optional. Specifies whether to add a watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
    //request.setIsShowWaterMark(true);
    /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable 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\"}}");
    /* Optional. The video category ID. */
    //request.setCateId(0);
    /* Optional. The video tags. Separate multiple tags with commas (,). */
    //request.setTags("Tag1,Tag2");
    /* Optional. The video description. */
    //request.setDescription("Video description");
    /* Optional. The thumbnail URL. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* Optional. The template group ID. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e5****");
    /* Optional. The workflow ID. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. The storage location. */
    //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. You must inherit VoDProgressListener. */
    /* This feature is disabled by default. If this feature is enabled, the server returns the upload details in the logs. If you do not want to receive the messages, disable this feature. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* Sets the implementation class of the interface that is used to generate STS information. */
    // request.setVoDRefreshSTSTokenListener(new RefreshSTSTokenImpl());
    /* The application ID. */
    //request.setAppId("app-100****");
    /* The region where ApsaraVideo VOD is activated. */
    //request.setApiRegionId("cn-shanghai");
    /* The region where the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");
    // If the region where the ECS instance is deployed is the same as the region where ApsaraVideo VOD is activated, the internal network upload feature is automatically enabled.
    /* Optional. The proxy settings. */
    //OSSConfig ossConfig = new OSSConfig();
    /* Required. The host address of the proxy server. */
    //ossConfig.setProxyHost("");
    /* Required. The port number of the proxy server. */
    //ossConfig.setProxyPort(-1);
    /* The protocol that is 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 requests. Default value: aliyun-sdk-java. */
    //ossConfig.setUserAgent("");
    /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
    //ossConfig.setProxyUsername("");
    /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
    //ossConfig.setProxyPassword("");
    //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 callback URL is invalid, the upload is not affected, and the service returns a video ID and an error code. In other cases, if the upload fails, no video ID is returned, and you must troubleshoot the issue based on the error code. */
        System.out.print("VideoId=" + response.getVideoId() + "\n");
        System.out.print("ErrorCode=" + response.getCode() + "\n");
        System.out.print("ErrorMessage=" + response.getMessage() + "\n");
    }
}
/**
 * Upload a network stream. This method supports resumable upload. You can upload a single file of up to 48.8 TB.
 * This method first downloads the file from the specified URL to a local disk and then uploads the file. Make sure that the local disk has sufficient space.
 * If the URL does not contain the file name extension, you must 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);
    /* The file name extension. */
    request.setFileExtension(fileExtension);
    /* The connection timeout period for downloading the online file. Unit: milliseconds. A value of 0 indicates no limit. */
    request.setDownloadConnectTimeout(1000);
    /* The read timeout period for downloading the online file. Unit: milliseconds. A value of 0 indicates no limit. */
    request.setDownloadReadTimeout(0);
    /* The local directory to which the file is downloaded. */
    request.setLocalDownloadFilePath("/Users/download");
    /* Optional. Specifies whether to add a watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
    //request.setShowWaterMark(true);
    /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable 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\"}}");
    /* Optional. The video category ID. */
    //request.setCateId(0);
    /* Optional. The video tags. Separate multiple tags with commas (,). */
    //request.setTags("Tag1,Tag2");
    /* Optional. The video description. */
    //request.setDescription("Video description");
    /* Optional. The thumbnail URL. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* Optional. The template group ID. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* Optional. The workflow ID. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. The storage location. */
    //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. You must inherit VoDProgressListener. */
    /* This feature is disabled by default. If this feature is enabled, the server returns the upload details in the logs. If you do not want to receive the messages, disable this feature. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* The application ID. */
    //request.setAppId("app-100****");
    /* The region where ApsaraVideo VOD is activated. */
    //request.setApiRegionId("cn-shanghai");
    /* The region where the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");
    // If the region where the ECS instance is deployed is the same as the region where ApsaraVideo VOD is activated, the internal network upload feature is automatically enabled.
     /* Optional. The proxy settings. */
     //OSSConfig ossConfig = new OSSConfig();
     /* Required. The host address of the proxy server. */
     //ossConfig.setProxyHost("");
     /* Required. The port number of the proxy server. */
     //ossConfig.setProxyPort(-1);
     /* The protocol that is 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 requests. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("");
     /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
     //ossConfig.setProxyUsername("");
     /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
     //ossConfig.setProxyPassword("");
     //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 callback URL is invalid, the upload is not affected, and the service returns a video ID and an error code. In other cases, if the upload fails, no video ID is returned, and you must troubleshoot the issue based on the error code. */
        System.out.print("VideoId=" + response.getVideoId() + "\n");
        System.out.print("ErrorCode=" + response.getCode() + "\n");
        System.out.print("ErrorMessage=" + response.getMessage() + "\n");
    }
}
/**
 * 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. Specifies whether to add the default watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
    //request.setShowWaterMark(true);
    /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable 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\"}}");
    /* Optional. The video category ID. */
    //request.setCateId(0);
    /* Optional. The video tags. Separate multiple tags with commas (,). */
    //request.setTags("Tag1,Tag2");
    /* Optional. The video description. */
    //request.setDescription("Video description");
    /* Optional. The thumbnail URL. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* Optional. The template group ID. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* Optional. The workflow ID. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. The storage location. */
    //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. You must inherit VoDProgressListener. */
    /* This feature is disabled by default. If this feature is enabled, the server returns the upload details in the logs. If you do not want to receive the messages, disable this feature. */
    //request.setProgressListener(new PutObjectProgressListener());
    /* The application ID. */
    //request.setAppId("app-100****");
    /* The region where ApsaraVideo VOD is activated. */
    //request.setApiRegionId("cn-shanghai");
    /* The region where the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");
    // If the region where the ECS instance is deployed is the same as the region where ApsaraVideo VOD is activated, the internal network upload feature is automatically enabled.
     /* Optional. The proxy settings. */
     //OSSConfig ossConfig = new OSSConfig();
     /* Required. The host address of the proxy server. */
     //ossConfig.setProxyHost("");
     /* Required. The port number of the proxy server. */
     //ossConfig.setProxyPort(-1);
     /* The protocol that is 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 requests. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("");
     /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
     //ossConfig.setProxyUsername("");
     /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
     //ossConfig.setProxyPassword("");
     //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 callback URL is invalid, the upload is not affected, and the service returns a video ID and an error code. In other cases, if the upload fails, no video ID is returned, and you must troubleshoot the issue based on the error code. */
        System.out.print("VideoId=" + response.getVideoId() + "\n");
        System.out.print("ErrorCode=" + response.getCode() + "\n");
        System.out.print("ErrorMessage=" + response.getMessage() + "\n");
    }
}
/**
 * Perform a 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. Specifies whether to add the default watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
    //request.setShowWaterMark(true);
    /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable 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\"}}");
    /* Optional. The video category ID. */
    //request.setCateId(0);
    /* Optional. The video tags. Separate multiple tags with commas (,). */
    //request.setTags("Tag1,Tag2");
    /* Optional. The video description. */
    //request.setDescription("Video description");
    /* Optional. The thumbnail URL. */
    //request.setCoverURL("http://cover.example.com/image_01.jpg");
    /* Optional. The template group ID. */
    //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
    /* Optional. The workflow ID. */
    //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
    /* Optional. The storage location. */
    //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. You must inherit VoDProgressListener. */
    /* This feature is disabled by default. If this feature is enabled, the server returns the upload details in the logs. If you do not want to receive the messages, disable this feature. */
    // request.setProgressListener(new PutObjectProgressListener());
     /* The application ID. */
    //request.setAppId("app-100****");
    /* The region where ApsaraVideo VOD is activated. */
    //request.setApiRegionId("cn-shanghai");
    /* The region where the ECS instance is deployed. */
    // request.setEcsRegionId("cn-shanghai");
    // If the region where the ECS instance is deployed is the same as the region where ApsaraVideo VOD is activated, the internal network upload feature is automatically enabled.
     /* Optional. The proxy settings. */
     //OSSConfig ossConfig = new OSSConfig();
     /* Required. The host address of the proxy server. */
     //ossConfig.setProxyHost("");
     /* Required. The port number of the proxy server. */
     //ossConfig.setProxyPort(-1);
     /* The protocol that is 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 requests. Default value: aliyun-sdk-java. */
     //ossConfig.setUserAgent("");
     /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
     //ossConfig.setProxyUsername("");
     /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
     //ossConfig.setProxyPassword("");
     //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 callback URL is invalid, the upload is not affected, and the service returns a video ID and an error code. In other cases, if the upload fails, no video ID is returned, and you must troubleshoot the issue based on the 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

Sample code

public class UploadVideoDemo {
    // Required: Specify your AccessKey pair.
    // An AccessKey pair from an Alibaba Cloud account can access all APIs. We recommend that you use a RAM user for API access or routine O&M.
    // Do not hard-code the AccessKey ID and AccessKey Secret in your project. Otherwise, the AccessKey pair may be leaked and all the resources in your account may be exposed to risks.
    // In this example, the AccessKey pair is obtained from environment variables. 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 an online M3U8 audio or video file.
        testUploadWebM3u8(accessKeyId, accessKeySecret);
    }
    /**
     * Uploads a local M3U8 audio or video file to ApsaraVideo VOD. By default, the M3U8 file and its TS files are in the same directory. If sliceFilenames is not specified, the TS file paths are parsed from the M3U8 file.
     *
     * @param request The request to upload a local M3U8 file.
     *                m3u8Filename: The absolute path of the local M3U8 index file. The TS file paths in the M3U8 file must be relative. These paths cannot contain URLs or absolute local paths.
     *                sliceFilenames: The list of the absolute paths of the TS files. If you specify this parameter, the specified paths are used. If you do not specify this parameter, the M3U8 file specified by m3u8Filename is 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"
        };
        // Optional. The list of absolute paths for the TS files. If you do not specify this parameter, the TS file paths are obtained by parsing the M3U8 file.
        request.setSliceFilenames(sliceFilenames);
        /* The part size for multipart upload. Default value: 2 MB. */
        request.setPartSize(2 * 1024 * 1024L);
        /* The number of concurrent threads for multipart upload. Default value: 1. This parameter affects CPU consumption. Set this value based on your server's configuration. */
        request.setTaskNum(1);
        /* Optional. Specifies whether to add a watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
        //request.setShowWaterMark(true);
        /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable 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\"}}");
        /* Optional. The video category ID. */
        //request.setCateId(-1L);
        /* Optional. The video tags. Separate multiple tags with commas (,). */
        //request.setTags("Tag1,Tag2");
        /* Optional. The video description. */
        //request.setDescription("Video description");
        /* Optional. The thumbnail URL. */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* Optional. The template group ID. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* Optional. The workflow ID. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* Optional. The storage location. */
        //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
        /* The application ID. */
        // request.setAppId("app-1000000");
        /* The region where ApsaraVideo VOD is activated. */
        // request.setApiRegionId("cn-shanghai");
        /* The region where the ECS instance is deployed. */
        // request.setEcsRegionId("cn-shanghai");
        /* Optional. The proxy settings. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The host address of the proxy server. */
        //ossConfig.setProxyHost("");
        /* Required. The port number of the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* The protocol that is 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 requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("");
        /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("");
        /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("");
        //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 an online M3U8 audio or video file to ApsaraVideo VOD. This method first downloads the file to a temporary local directory and then uploads the file to ApsaraVideo VOD storage. Make sure that the local disk has sufficient space.
     *
     * @param request The request to upload an online M3U8 file.
     *                m3u8FileURL: The URL of the online M3U8 index file. The TS file paths in the M3U8 file must be relative. These paths cannot contain URLs or absolute local paths.
     *                sliceFileURLs: The list of the URLs of the TS files. You must construct the URLs of the TS files.
     */
    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 URLs of the TS files. If you do not specify this parameter, the TS file URLs are obtained by parsing the m3u8FileURL parameter.
        request.setSliceFileURLs(sliceFileURLs);
        /* The temporary storage directory for the downloaded files. You can specify a custom directory. If you do not specify this parameter, the files are saved to the current working directory. */
        // request.setGlobalLocalFilePath("/User/download/");
        /* The part size for multipart upload. Default value: 2 MB. */
        request.setPartSize(2 * 1024 * 1024L);
        /* The number of concurrent threads for multipart upload. Default value: 1. This parameter affects CPU consumption. Set this value based on your server's configuration. */
        request.setTaskNum(1);
        /* Optional. Specifies whether to add a watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
        //request.setShowWaterMark(true);
        /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable 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\"}}");
        /* Optional. The video category ID. */
        //request.setCateId(-1L);
        /* Optional. The video tags. Separate multiple tags with commas (,). */
        //request.setTags("Tag1,Tag2");
        /* Optional. The video description. */
        //request.setDescription("Video description");
        /* Optional. The thumbnail URL. */
        //request.setCoverURL("http://cover.example.com/sample.jpg");
        /* Optional. The template group ID. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* Optional. The workflow ID. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* Optional. The storage location. */
        //request.setStorageLocation("in-2017032321****-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /* The application ID. */
        //request.setAppId("app-100****");
        /* The region where ApsaraVideo VOD is activated. */
        //request.setApiRegionId("cn-shanghai");
        /* The region where the ECS instance is deployed. */
        // request.setEcsRegionId("cn-shanghai");
        /* Optional. The proxy settings. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The host address of the proxy server. */
        //ossConfig.setProxyHost("");
        /* Required. The port number of the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* The protocol that is 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 requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("");
        /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("");
        /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("");
        //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

For large files (GBs or TBs) or cross-region uploads (for example, from the Chinese mainland to the Singapore storage region), enable upload acceleration. Enable upload acceleration. After enabling it, add the AccelerateConfig key-value pair to the UserData object in the upload configuration. Create the UserData object if it does not exist. Example:

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

Parameters

Parameter

Type

Description

Type

String

The service for which to enable upload acceleration. Set this value to oss.

Domain

String

The accelerated endpoint of your bucket. The default protocol is HTTPS.

Note

Use the accelerated endpoint provided after you enable this feature, such as vod-*******.oss-accelerate.aliyuncs.com.

Scenario 2: Upload images

Show sample code

public class UploadImageDemo {
    // Required. The AccessKey pair of your Alibaba Cloud account.
    // An Alibaba Cloud account's AccessKey pair can access all APIs. We recommend that you use a RAM user for API access or routine operations.
    // We strongly recommend that you do not hard-code your AccessKey ID and AccessKey secret in your project code. This can leak your credentials and compromise the security of all resources in your account.
    // This example obtains an AccessKey pair from environment variables. 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 an image from a local file.
         testUploadImageLocalFile(accessKeyId, accessKeySecret);
        // 2. Upload an image by using a file or network stream.
         testUploadImageStream(accessKeyId, accessKeySecret);
    }
    /**
     * Uploads an image from a local file.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageLocalFile(String accessKeyId, String accessKeySecret) {
        /* Required. 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. The image file extension. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* Optional. The image title. The title must be in UTF-8 and cannot exceed 128 bytes. */
        //request.setTitle("Image title");
        /* Optional. The image tags. You can add up to 16 tags, separated by commas (,). Each tag must be in UTF-8 and cannot exceed 32 bytes. */
        //request.setTags("Tag1,Tag2");
        /* Optional. The storage location. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* For streaming upload, the InputStream parameter is required. The fileName parameter (the name of the source file) is optional. Example: 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. You must inherit from VoDProgressListener. */
        /* This feature is disabled by default. If enabled, the server logs upload details during the upload process. Disable this feature if you do not need these logs. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Optional. The application ID. */
        //request.setAppId("app-100****");
        /* The region ID for the ApsaraVideo VOD access point. */
        //request.setApiRegionId("cn-shanghai");
        /* Optional. Configures a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server's host address. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server's 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 header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter 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");
        }
    }
    /**
     * Uploads an image from a stream. This method supports both file and network streams.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageStream(String accessKeyId, String accessKeySecret) {
        /* Required. The type of the image. Valid values: default, cover, and watermark. */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        /* Optional. The image file extension. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* Optional. The image title. The title must be in UTF-8 and cannot exceed 128 bytes. */
        //request.setTitle("Image title");
        /* Optional. The image tags. You can add up to 16 tags, separated by commas (,). Each tag must be in UTF-8 and cannot exceed 32 bytes. */
        //request.setTags("Tag1,Tag2");
        /* Optional. The storage location. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* For streaming upload, the InputStream parameter is required. The fileName parameter (the name of the source file) is optional. Example: filename.png. */
        //request.setFileName("Test file name.png");
        /* Enables the default upload progress callback. */
        // request.setPrintProgress(true);
        /* Sets a custom upload progress callback. You must inherit from VoDProgressListener. */
        /* This feature is disabled by default. If enabled, the server logs upload details during the upload process. Disable this feature if you do not need these logs. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Optional. The application ID. */
        //request.setAppId("app-1000000");
        /* Optional. Configures a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server's host address. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server's 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 header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required if you use 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 the image 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

Sample code

public class UploadAttachedMediaDemo {
    // Required. The AccessKey pair of your account.
    // An AccessKey pair for an Alibaba Cloud account grants full access to all API operations. We recommend using a RAM user for API access and routine O&M.
    // To prevent leaks, do not hard-code your AccessKey ID and AccessKey Secret in your project. A leaked AccessKey pair can compromise the security of all resources in your account.
    // This example retrieves an AccessKey pair from environment variables for identity verification. 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 auxiliary media assets.
        // Upload an auxiliary media asset from a local file.
        testUploadAttachedMediaLocalFile(accessKeyId, accessKeySecret);
        // Upload an auxiliary media asset by using streaming upload (file stream and network stream).
        testUploadAttachedMediaStream(accessKeyId, accessKeySecret);
    }
 /**
     * Uploads a local auxiliary media asset.
     *
     * @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);
        /* Optional. The tags. Separate multiple tags with commas. */
        request.setTags("tag1,tag2");
        /* Optional. The description. */
        request.setDescription("test_desc");
        /* Optional. The storage location. */
        request.setStorageLocation("out-20170323225118266-5l3hs5****.oss-cn-shanghai.aliyuncs.com");
        /* The access region of ApsaraVideo VOD. */
        request.setApiRegionId("cn-shanghai");
        /* The application ID. */
        //request.setAppId("app-1000000");
        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The proxy host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. The proxy 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 header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter 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");
        }
    }
     /**
     * Uploads an auxiliary media asset by using streaming upload. 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 from a file stream.
        InputStream fileStream = getFileStream(filename);
        request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
        request.setInputStream(fileStream);
        // 2. Upload from 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);
        /* Optional. The tags. Separate multiple tags with commas. */
        request.setTags("tag1,tag2");
        /* Optional. The description. */
        request.setDescription("test_desc");
        /* Optional. The storage location. */
        request.setStorageLocation("out-20170323225118266-5l3****wa.oss-cn-shanghai.aliyuncs.com");
        /* The access region of ApsaraVideo VOD. */
        request.setApiRegionId("cn-shanghai");
        /* The application ID. */
        // request.setAppId("app-1000000");
        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The proxy host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. The proxy 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 header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter 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 features

  • Upload progress bar

    The PutObjectProgressListener.java file in the sample directory provides an upload progress callback implementation.

    This class implements the VoDProgressListener interface. A ProgressEvent object reports file upload progress to OSS, and you can add custom logic for each event.

    The following code provides an example.

    Show sample code

    /**
     * An implementation of a listener for upload progress callbacks.
     * This callback is invoked only if you enable upload progress notifications.
     * A callback event is triggered when a multipart upload to OSS succeeds or fails. You can implement custom logic to handle the event.
     * When uploading an audio or video file, this callback provides the `videoId`, which you can use to manage the file.
     * When uploading an image, this callback provides the `imageId`, which you can use to manage the image.
     */
    public class PutObjectProgressListener implements VoDProgressListener {
        /**
         * Number of bytes that have been successfully uploaded to OSS.
         */
        private long bytesWritten = 0;
        /**
         * Total size of the source file in bytes.
         */
        private long totalBytes = -1;
        /**
         * Indicates whether the upload completed successfully.
         */
        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) {
                // Indicates that the upload started.
                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;
                // Provides 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;
                // Indicates the number of bytes that have been transferred.
                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;
                // Indicates that the transfer is complete.
                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;
                // Indicates that the transfer 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 shows how to refresh a temporary token.

    The following code provides an example.

    Show sample code

    /**
     * @author vod
     * An implementation that retrieves a temporary token from Security Token Service (STS).
     * @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

Issue 1: Missing dependency errors

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

  2. In the top menu bar, select Build > Rebuild Project.

  3. Copy aliyun-java-vod-upload-1.4.15.jar to your project's resources directory and add a local Maven 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 adding the local dependency.

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