すべてのプロダクト
Search
ドキュメントセンター

ApsaraVideo VOD:Java SDKによるファイルのアップロード

最終更新日:Aug 06, 2026

Java 用のサーバー側アップロード SDK を使用して、オーディオ、ビデオ、画像、補助メディアファイルを ApsaraVideo VOD にアップロードします。

概要

Java アップロード SDK は、ApsaraVideo VOD のアップロードプロセスに従います。基本的な手順は次のとおりです。

  1. 前提条件を満たします。

  2. Java アップロード SDK を統合します。

  3. アップロードロジック (主にアップロード設定) を実装します。

前提条件

  • ApsaraVideo VOD がアクティブ化されていること。詳細については、「ApsaraVideo VOD をアクティブ化する」をご参照ください。

  • 指定リージョンのストレージパスやコールバック設定など、アップロードに必要なシステム設定が構成されていること。詳細については、「ストレージバケットを管理する」および「コールバックを設定する」をご参照ください。

  • RAM ユーザーが作成され、ApsaraVideo VOD へのアクセスに使用されていること。Alibaba Cloud アカウントの AccessKey ペアの漏洩によるセキュリティリスクを防ぐため、RAM ユーザーを作成し、ApsaraVideo VOD へのアクセスに必要な権限を RAM ユーザーに付与することをお勧めします。その後、RAM ユーザーの AccessKey ペア を使用して ApsaraVideo VOD にアクセスできます。詳細については、「RAM ユーザーを作成して権限を付与する」をご参照ください。

  • ALIBABA_CLOUD_ACCESS_KEY_ID および ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境変数を設定します。詳細については、「Linux、macOS、および Windows で環境変数を設定する」をご参照ください。

    重要
    • Alibaba Cloud アカウントの AccessKey ペアは、すべての API 操作に対する権限を持っています。 API 操作の呼び出しや日常的な O&M の実行には、RAM ユーザーの AccessKey ペアを使用することをお勧めします。

    • AccessKey ID と AccessKey シークレットをプロジェクトコードにハードコードしないことをお勧めします。 そうしないと、AccessKey ペアが漏洩し、アカウント内のすべてのリソースのセキュリティが侵害される可能性があります。

  • オプション。Security Token Service ( STS ) を使用して ApsaraVideo VOD にアクセスする場合、RAM ユーザーのロールが作成され、そのロールには ApsaraVideo VOD へのアクセスに必要な権限が付与されます。詳細については、「STS を使用して動画をアップロードする」をご参照ください。

    説明

    詳細については、「クレデンシャルと STS の比較」をご参照ください。

Java 用アップロード SDK の統合

説明

この例では、Java 1.8+ と Java 用アップロード SDK 1.4.15 を使用します。手順はバージョンによって異なる場合があります。この SDK は、Maven などによる依存関係の自動解決に対応していないため、JAR ファイルを手動でプロジェクトにインポートする必要があります。トラブルシューティング

  1. Java 用アップロード SDK とサンプルコードをダウンロードします。

  2. ダウンロードしたパッケージを解凍します。

    VODUploadDemo-java-1.4.15.zip を解凍すると、次のフォルダーが展開されます。

    • lib:アップロード SDK に必要な JAR パッケージ。

    • sample:アップロード SDK のサンプルコード。

  3. JAR パッケージをインポートします。

    • Eclipse: プロジェクトを右クリックし、[プロパティー] > [Java のビルド・パス] > [JAR の追加] を選択し、解凍した VODUploadDemo-java-1.4.15 フォルダーに移動して、lib ディレクトリからすべての jar ファイルを追加します。

    • IntelliJ IDEA: [ファイル] > [プロジェクト構造] > [モジュール] を選択し、右側の [依存関係] をクリックし、[+] をクリックし、次に [JAR またはディレクトリ] をクリックします。解凍した VODUploadDemo-java-1.4.15 ディレクトリに移動し、lib ディレクトリからすべての jar ファイルを追加します。

    重要

    JAR パッケージをインポートした後、依存関係を構成します。

  4. Alibaba Cloud SDK for Java、OSS SDK、ApsaraVideo VOD サーバーサイド SDK、および ApsaraVideo VOD アップロード SDK の依存関係を追加します。

    重要
    • 記載されているすべての依存関係が必要です。いずれかが欠けていると、統合が失敗します。

    • 最新の JAR パッケージ (aliyun-java-vod-upload-1.4.15.jar) を使用する場合は、aliyun-sdk-oss のバージョンが 3.9.0 以降、aliyun-java-sdk-vod のバージョンが 2.16.11 以降であることを確認してください。

    • ApsaraVideo VOD は、中国 (上海)、中国 (深圳)、中国 (北京) リージョンで利用できます。中国 (深圳) または中国 (北京) へのアップロードの場合:アップロード SDK 1.4.14 以前では aliyun-java-sdk-vod 2.15.11+ および aliyun-java-sdk-core 4.4.5+ が必要です。アップロード SDK 1.4.15 以降では aliyun-java-sdk-vod 2.16.11+ および aliyun-java-sdk-core 4.4.5+ が必要です。

    依存関係を表示

       <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>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </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.

      重要

      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.

重要

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.

説明

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

シナリオ 2:画像のアップロード

サンプルコードを表示

public class UploadImageDemo {
    // 必須。 Alibaba Cloud アカウントの AccessKey ペア。
    // Alibaba Cloud アカウントの AccessKey ペアは、すべての API にアクセスできます。API へのアクセスや定常運用には、RAM ユーザーを使用することを推奨します。
    // プロジェクトコードに AccessKey ID と AccessKey secret をハードコードしないことを強く推奨します。認証情報が漏洩し、アカウント内のすべてのリソースのセキュリティが侵害されるおそれがあります。
    // この例では、環境変数から AccessKey ペアを取得します。サンプルコードを実行する前に、ALIBABA_CLOUD_ACCESS_KEY_ID と ALIBABA_CLOUD_ACCESS_KEY_SECRET の環境変数を設定してください。
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    public static void main(String[] args) {
        // 画像をアップロードします。
        // 1. ローカルファイルから画像をアップロードします。
         testUploadImageLocalFile(accessKeyId, accessKeySecret);
        // 2. ファイルストリームまたはネットワークストリームを使用して画像をアップロードします。
         testUploadImageStream(accessKeyId, accessKeySecret);
    }
    /**
     * ローカルファイルから画像をアップロードします。
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageLocalFile(String accessKeyId, String accessKeySecret) {
        /* 必須。 イメージタイプ。有効な値:default、cover、watermark。 */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        request.setImageType("cover");
        /* 任意。 画像ファイルの拡張子。有効な値:png、jpg、jpeg。 */
        //request.setImageExt("png");
        /* 任意。 画像タイトル。タイトルは UTF-8 で、128 バイトを超えることはできません。 */
        //request.setTitle("Image title");
        /* 任意。 イメージタグ。最大 16 個のタグを追加できます。複数のタグはカンマ (,) で区切ります。各タグは UTF-8 で、32 バイトを超えることはできません。 */
        //request.setTags("Tag1,Tag2");
        /* 任意。 ストレージロケーション。 */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* ローカルファイルアップロードの場合、fileName パラメーター (ローカルファイルのフルパス) は必須です。 */
        String fileName = "/Users/demo/png/test.png";
        request.setFileName(fileName);
        /* デフォルトのアップロード進捗状況のコールバックを無効にします。 */
        //request.setPrintProgress(false);
        /* カスタムのアップロード進捗状況のコールバックを設定します。VoDProgressListener を継承する必要があります。 */
        /* この機能はデフォルトで無効です。有効にすると、サーバーはアップロード中にアップロードの詳細をログに記録します。これらのログが不要な場合は、この機能を無効にしてください。 */
        // request.setProgressListener(new PutObjectProgressListener());
        /* 任意。 アプリケーション ID。 */
        //request.setAppId("app-100****");
        /* ApsaraVideo VOD のアクセスポイントのリージョン ID。 */
        //request.setApiRegionId("cn-shanghai");
        /* 任意。 プロキシを設定します。 */
        //OSSConfig ossConfig = new OSSConfig();
        /* <必須> プロキシサーバーのホストアドレス。 */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <必須> プロキシサーバーのポート。 */
        //ossConfig.setProxyPort(8080);
        /* OSS への接続に使用するプロトコル。有効な値:HTTP、HTTPS。デフォルト値:HTTP。 */
        //ossConfig.setProtocol("HTTP");
        /* HTTP リクエストの User-Agent ヘッダー。デフォルト値:aliyun-sdk-java。 */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* プロキシサーバー認証に使用するユーザー名。このパラメーターは、HTTPS プロトコルを使用する場合に必須です。 */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* プロキシサーバー認証に使用するパスワード。このパラメーターは、HTTPS プロトコルを使用する場合に必須です。 */
        //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");
        }
    }
    /**
     * ストリームから画像をアップロードします。このメソッドは、ファイルストリームとネットワークストリームの両方に対応しています。
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageStream(String accessKeyId, String accessKeySecret) {
        /* 必須。 イメージタイプ。有効な値:default、cover、watermark。 */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        /* 任意。 画像ファイルの拡張子。有効な値:png、jpg、jpeg。 */
        //request.setImageExt("png");
        /* 任意。 画像タイトル。タイトルは UTF-8 で、128 バイトを超えることはできません。 */
        //request.setTitle("Image title");
        /* 任意。 イメージタグ。最大 16 個のタグを追加できます。複数のタグはカンマ (,) で区切ります。各タグは UTF-8 で、32 バイトを超えることはできません。 */
        //request.setTags("Tag1,Tag2");
        /* 任意。 ストレージロケーション。 */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* ストリーミングアップロードの場合、InputStream パラメーターが必須です。fileName パラメーター (ソースファイル名) は任意です。例:filename.png。 */
        //request.setFileName("Test file name.png");
        /* デフォルトのアップロード進捗状況のコールバックを有効にします。 */
        // request.setPrintProgress(true);
        /* カスタムのアップロード進捗状況のコールバックを設定します。VoDProgressListener を継承する必要があります。 */
        /* この機能はデフォルトで無効です。有効にすると、サーバーはアップロード中にアップロードの詳細をログに記録します。これらのログが不要な場合は、この機能を無効にしてください。 */
        // request.setProgressListener(new PutObjectProgressListener());
        /* 任意。 アプリケーション ID。 */
        //request.setAppId("app-1000000");
        /* 任意。 プロキシを設定します。 */
        //OSSConfig ossConfig = new OSSConfig();
        /* <必須> プロキシサーバーのホストアドレス。 */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <必須> プロキシサーバーのポート。 */
        //ossConfig.setProxyPort(8080);
        /* OSS への接続に使用するプロトコル。有効な値:HTTP、HTTPS。デフォルト値:HTTP。 */
        //ossConfig.setProtocol("HTTP");
        /* HTTP リクエストの User-Agent ヘッダー。デフォルト値:aliyun-sdk-java。 */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* プロキシサーバー認証に使用するユーザー名。このパラメーターは、HTTPS プロトコルを使用する場合に必須です。 */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* プロキシサーバー認証に使用するパスワード。このパラメーターは、HTTPS プロトコルを使用する場合に必須です。 */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        // 1. ファイルストリームをアップロードします。
        // InputStream fileStream = getFileStream(request.getFileName());
        // if (fileStream != null) { 
        //     request.setInputStream(fileStream);
        // }
        // 2. ネットワークストリームをアップロードします。
        String url = "http://test.aliyun.com/image/default/test.png";
        InputStream urlStream = getUrlStream(url);
        if (urlStream != null) {
            request.setInputStream(urlStream); 
       }
        // 画像のアップロードを開始します。
        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;
    }
}          
説明

デフォルトでは、ImageURL の有効期間は 3,600 秒 (1 時間) です。この有効期間はシステムによって固定されており、API パラメーターや SDK 設定ではカスタマイズできません。有効期限は OSS の署名付き URL のメカニズムに基づいており、CDN コンソールで設定できる CDN URL 署名の有効期限とは独立して計算されます。そのため、2 つの有効期限が異なる場合がありますが、これは想定どおりの動作です。

シナリオ 3:補助メディアアセットのアップロード

サンプルコード

public class UploadAttachedMediaDemo {
    // 必須。アカウントの AccessKey ペアです。
    // Alibaba Cloud アカウントの AccessKey ペアは、すべての API オペレーションへの完全なアクセス権を付与します。API アクセスおよび定常運用には、RAM ユーザーを使用することを推奨します。
    // 漏洩を防ぐため、AccessKey ID と AccessKey Secret をプロジェクトにハードコードしないでください。AccessKey ペアが漏洩すると、アカウント内のすべてのリソースのセキュリティが損なわれる可能性があります。
    // この例では、ID 検証のために環境変数から AccessKey ペアを取得します。サンプルコードを実行する前に、ALIBABA_CLOUD_ACCESS_KEY_ID および ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境変数を構成してください。
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    public static void main(String[] args) {
        // 補助メディアアセットをアップロードします。
        // ローカルファイルから補助メディアアセットをアップロードします。
        testUploadAttachedMediaLocalFile(accessKeyId, accessKeySecret);
        // ストリーミングアップロード (ファイルストリームおよびネットワークストリーム) を使用して補助メディアアセットをアップロードします。
        testUploadAttachedMediaStream(accessKeyId, accessKeySecret);
    }
 /**
     * ローカルの補助メディアアセットをアップロードします。
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaLocalFile(String accessKeyId, String accessKeySecret) {
        /* ビジネスタイプ。 */
        String businessType = "watermark";
        /* ファイル名拡張子。 */
        String mediaExt = "png";
        String filename = "/Users/demo/png/test.png";
        UploadAttachedMediaRequest request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
        request.setFileName(filename);
        /* タイトル。 */
        request.setTitle("test_attached_media");
        /* カテゴリ ID。 */
        request.setCateId(-1L);
        /* オプション。タグ。複数のタグはカンマで区切ります。 */
        request.setTags("tag1,tag2");
        /* オプション。説明。 */
        request.setDescription("test_desc");
        /* オプション。ストレージロケーション。 */
        request.setStorageLocation("out-20170323225118266-5l3hs5****.oss-cn-shanghai.aliyuncs.com");
        /* ApsaraVideo VOD のアクセスリージョン。 */
        request.setApiRegionId("cn-shanghai");
        /* アプリケーション ID。 */
        //request.setAppId("app-1000000");
        /* オプション。プロキシの設定。 */
        //OSSConfig ossConfig = new OSSConfig();
        /* 必須。プロキシホスト。 */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* 必須。プロキシポート。 */
        //ossConfig.setProxyPort(-1);
        /* OSS への接続に使用するプロトコル。有効な値:HTTP および HTTPS。デフォルト値:HTTP。 */
        //ossConfig.setProtocol("HTTP");
        /* HTTP リクエストの User-Agent ヘッダー。デフォルト値:aliyun-sdk-java。 */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* プロキシサーバー認証のユーザー名。プロキシサーバーで認証が必要な場合に設定します。 */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* プロキシサーバー認証のパスワード。プロキシサーバーで認証が必要な場合に設定します。 */
        //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");
        }
    }
     /**
     * ストリーミングアップロードを使用して補助メディアアセットをアップロードします。このメソッドはファイルストリームとネットワークストリームをサポートします。
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaStream(String accessKeyId, String accessKeySecret) {
        /* ビジネスタイプ。 */
        String businessType = "watermark";
        /* ファイル名拡張子。 */
        String mediaExt = "png";
        String filename = "/Users/demo/png/test.png";
        UploadAttachedMediaRequest request;
        // 1. ファイルストリームからアップロードします。
        InputStream fileStream = getFileStream(filename);
        request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
        request.setInputStream(fileStream);
        // 2. ネットワークストリームからアップロードします。
//        String url = "http://test.aliyun.com/image//test.png";
//        InputStream urlStream = getUrlStream(url);
//        request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
//        request.setInputStream(urlStream);
        /* タイトル。 */
        request.setTitle("test_attached_media");
        /* カテゴリ ID。 */
        request.setCateId(-1L);
        /* オプション。タグ。複数のタグはカンマで区切ります。 */
        request.setTags("tag1,tag2");
        /* オプション。説明。 */
        request.setDescription("test_desc");
        /* オプション。ストレージロケーション。 */
        request.setStorageLocation("out-20170323225118266-5l3****wa.oss-cn-shanghai.aliyuncs.com");
        /* ApsaraVideo VOD のアクセスリージョン。 */
        request.setApiRegionId("cn-shanghai");
        /* アプリケーション ID。 */
        // request.setAppId("app-1000000");
        /* オプション。プロキシの設定。 */
        //OSSConfig ossConfig = new OSSConfig();
        /* 必須。プロキシホスト。 */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* 必須。プロキシポート。 */
        //ossConfig.setProxyPort(-1);
        /* OSS への接続に使用するプロトコル。有効な値:HTTP および HTTPS。デフォルト値:HTTP。 */
        //ossConfig.setProtocol("HTTP");
        /* HTTP リクエストの User-Agent ヘッダー。デフォルト値:aliyun-sdk-java。 */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* プロキシサーバー認証のユーザー名。プロキシサーバーで認証が必要な場合に設定します。 */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* プロキシサーバー認証のパスワード。プロキシサーバーで認証が必要な場合に設定します。 */
        //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");
        }
    }
    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;
    }
}

高度な機能

  • アップロードプログレスバー

    sample ディレクトリにある PutObjectProgressListener.java ファイルには、アップロード進捗コールバックの実装が含まれています。

    このクラスは VoDProgressListener インターフェイスを実装します。ProgressEvent オブジェクトは OSS へのファイルアップロードの進捗を報告し、各イベントに対してカスタムロジックを追加できます。

    次のコードは一例です。

    サンプルコードの表示

    /**
     * アップロード進捗コールバックのリスナーの実装。
     * このコールバックは、アップロード進捗通知を有効にした場合にのみ呼び出されます。
     * OSS へのマルチパートアップロードが成功または失敗したときにコールバックイベントがトリガーされます。イベントを処理するためのカスタムロジックを実装できます。
     * オーディオまたはビデオファイルをアップロードする際、このコールバックによって `videoId` が提供され、これを使用してファイルを管理できます。
     * 画像をアップロードする際、このコールバックによって `imageId` が提供され、これを使用して画像を管理できます。
     */
    public class PutObjectProgressListener implements VoDProgressListener {
        /**
         * OSS に正常にアップロードされたバイト数。
         */
        private long bytesWritten = 0;
        /**
         * ソースファイルの合計サイズ (バイト単位)。
         */
        private long totalBytes = -1;
        /**
         * アップロードが正常に完了したかどうかを示します。
         */
        private boolean succeed = false;
        /**
         * ビデオ ID。
         */
        private String videoId;
        /**
         * イメージ ID。
         */
        private String imageId;
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
                // アップロードの開始を示します。
                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;
                // アップロードされるファイルの合計サイズが通知されます。このイベントは、ローカルファイルのアップロードでのみサポートされます。
                case REQUEST_CONTENT_LENGTH_EVENT:
                    this.totalBytes = bytes;
                    System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS.");
                    break;
                // 転送されたバイト数を示します。
                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 subtotal: " + "(" + this.bytesWritten + ")");
                    }
                    break;
                // 転送の完了を示します。
                case TRANSFER_COMPLETED_EVENT:
                    this.succeed = true;
                    if (videoId != null) {
                        System.out.println("Succeed to upload videoId " + videoId + ". Total " + this.bytesWritten + " bytes have been transferred.");
                    }
                    if (imageId != null) {
                        System.out.println("Succeed to upload imageId " + imageId + ". Total " + this.bytesWritten + " bytes have been transferred.");
                    }
                    break;
                // 転送の失敗を示します。
                case TRANSFER_FAILED_EVENT:
                    if (videoId != null) {
                        System.out.println("Failed to upload videoId " + videoId + ". " + this.bytesWritten + " bytes have been transferred.");
                    }
                    if (imageId != null) {
                        System.out.println("Failed to upload imageId " + imageId + ". " + this.bytesWritten + " bytes have been transferred.");
                    }
                    break;
                default:
                    break;
            }
        }
        public boolean isSucceed() {
            return succeed;
        }
        public void onVidReady(String videoId) {
            setVideoId(videoId);
        }
        public void onImageIdReady(String imageId) {
            setImageId(imageId);
        }
        public String getVideoId() {
            return videoId;
        }
        public void setVideoId(String videoId) {
            this.videoId = videoId;
        }
        public String getImageId() {
            return imageId;
        }
        public void setImageId(String imageId) {
            this.imageId = imageId;
        }
    }
                        
  • 一時トークンの更新

    sample ディレクトリにある RefreshSTSTokenImpl.java ファイルは、一時トークンを更新する方法の例です。

    次のコードは一例です。

    サンプルコードの表示

    /**
     * @author vod
     * 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;
        }
    }

よくある質問

問題 1:依存関係の欠落エラー

  1. Maven プロジェクトで、右側の [Maven] をクリックし、[m] アイコンをクリックして、mvn idea:module を入力してリソースを再読み込みします。

  2. 上部のメニューバーで、[Build] > [Rebuild Project] を選択します。

  3. aliyun-java-vod-upload-1.4.15.jar をプロジェクトのリソースディレクトリにコピーし、ローカルの Maven 依存関係を追加します:

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

    ローカル依存関係を追加した後の Maven 依存関係のサンプルです。

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

問題 2: M3U8 ファイルのアップロード時の NoClassDefFoundError

M3U8 ファイルをアップロードすると、次のエラーが発生します:

java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3/StringUtils

このエラーは、Java 用アップロード SDK が内部で依存している commons-lang3 ライブラリが依存関係リストに含まれていないために発生します。この問題を解決するには、次の依存関係を pom.xml ファイルに追加して、プロジェクトをリビルドしてください:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>