このトピックでは、アップロードSDK for Javaを使用してメディアファイルをApsaraVideo VODにアップロードする方法について説明します。
概要
Java用アップロードSDKは、ApsaraVideo VOD SDKの一般的なプロセスに従います。 詳細については、「アップロードプロセス」をご参照ください。 プロセスには次のステップが含まれます。
このトピックの前提条件セクションで説明されているように、設定を完了します。 詳細は、「前提条件 (Prerequisites)」をご参照ください。
Java用のアップロードSDKを統合します。 詳細については、「Java用アップロードSDKの統合」をご参照ください。
アップロード情報を設定して、アップロードロジックを実装します。
オーディオファイルまたはビデオファイルをアップロードする方法の詳細については、「シナリオ1: オーディオファイルまたはビデオファイルをアップロードする」をご参照ください。
画像のアップロード方法の詳細については、「シナリオ2: 画像のアップロード」をご参照ください。
補助メディアアセットをアップロードする方法の詳細については、「シナリオ3: 補助メディアアセットのアップロード」をご参照ください。
高度な機能の詳細については、「高度な機能」をご参照ください。
前提条件
ApsaraVideo VODが有効化されています。 詳細については、「ApsaraVideo VODの有効化」をご参照ください。
指定されたリージョンのストレージパスやコールバック設定など、アップロードに必要なシステム設定が構成されます。 詳細については、「ストレージバケットの管理」および「コールバックの設定」をご参照ください。
RAMユーザーが作成され、ApsaraVideo VODへのアクセスに使用されます。 Alibaba CloudアカウントのAccessKeyペアの漏洩によるセキュリティリスクを防ぐため、RAMユーザーを作成し、ApsaraVideo VODへのアクセスに必要な権限をRAMユーザーに付与することを推奨します。 その後、RAMユーザーのAccessKeyペアを使用してApsaraVideo VODにアクセスできます。 詳細については、「Create and grant permissions to a RAM user」をご参照ください。
ALIBABA_CLOUD_ACCESS_KEY_IDおよびALIBABA_CLOUD_ACCESS_KEY_SECRET環境変数を設定します。 詳細については、「Linux、macOS、およびWindowsでの環境変数の設定」をご参照ください。
重要Alibaba CloudアカウントのAccessKeyペアには、すべてのAPI操作に対する権限があります。 RAMユーザーのAccessKeyペアを使用して、API操作を呼び出したり、ルーチンのO&Mを実行したりすることを推奨します。
AccessKey IDとAccessKeyシークレットをプロジェクトコードにハードコードしないことを推奨します。 そうしないと、AccessKeyペアが漏洩し、アカウント内のすべてのリソースのセキュリティが侵害される可能性があります。
オプションです。 RAMユーザー用にロールが作成され、Security Token Service (STS) を使用してApsaraVideo VODにアクセスする場合は、ApsaraVideo VODにアクセスするために必要な権限がロールに付与されます。 詳細については、「STSを使用した動画のアップロード」をご参照ください。
説明STSを使用できるシナリオの詳細については、「資格情報とSTSの比較」をご参照ください。
Java用アップロードSDKの統合
次の例では、Java 1.8以降とJava V1.4.15用のアップロードSDKが使用されています。 ビジネス要件に基づいて他のバージョンを使用できます。 依存関係を直接追加してアップロードSDKを統合することはできません。 JARパッケージをダウンロードしてプロジェクトにインポートする必要があります。 アップロードSDK For Javaを統合するときに発生する可能性のあるエラーのトラブルシューティング方法の詳細については、「トラブルシューティング」をご参照ください。
Java用アップロードSDKとサンプルコードを含むパッケージをダウンロードします。
説明最新バージョンのアップロードSDK For Javaのダウンロードリンクの詳細については、「SDKのダウンロード」をご参照ください。 過去のバージョンのアップロードSDK For Javaのダウンロードリンクの詳細については、「アップロードSDK for Javaのリリースノート」をご参照ください。
完全なサンプルコードの詳細については、アップロードSDK For javaのパッケージを解凍するディレクトリにあるsample/UploadVideoDemo. Javaファイルをご参照ください。
パッケージを解凍します。
この例では、VODUploadDemo-java-1.4.15.zipパッケージを使用しています。 次のサブフォルダがパッケージから抽出されます。
lib
: アップロードSDK for JavaのJARパッケージを格納します。sample
: アップロードSDK for Javaのサンプルコードを格納します。
JARパッケージをインポートします。
Eclipseでプロジェクト名を右クリックし、[プロパティ] > [Javaビルドパス] > [JARの追加] を選択します。 解凍されたVODUploadDemo-java-1.4.15フォルダを見つけ、
lib
のすべてのJARパッケージをプロジェクトに追加します。IntelliJ IDEAでプロジェクトを開き、[ファイル] > [プロジェクト構造] > [モジュール] を選択します。 [依存関係] タブの右側にある [+] アイコンをクリックし、[JARまたはディレクトリ] を選択します。 解凍されたVODUploadDemo-java-1.4.15フォルダを見つけ、
lib
のすべてのJARパッケージをプロジェクトに追加します。
重要JARパッケージをインポートした後、依存関係を設定する必要があります。
Alibaba Cloud SDK for Java、Object Storage Service (OSS) SDK、ApsaraVideo VOD SDK、ApsaraVideo VODサーバーアップロードSDKなどの依存関係を追加します。
重要上記の依存関係をすべて統合する必要があります。 そうでなければ、統合は失敗します。
パッケージaliyun-java-vod-upload-1.4.15.jarの最新バージョンをダウンロードする場合は、aliyun-sdk-ossのバージョンがV3.9.0以降、aliyun-java-sdk-vodのバージョンがV2.16.11以降であることを確認してください。
ApsaraVideo VODは、中国 (上海) 、中国 (深セン) 、中国 (北京) の各リージョンでサポートされています。 Java V1.4.14以前のアップロードSDKを使用してメディアファイルを中国 (深セン) または中国 (北京) リージョンにアップロードする場合は、aliyun-java-sdk-vod V2.15.11以降およびaliyun-java-sdk-core V4.4.5以降を使用する必要があります。 Java V1.4.15以降のアップロードSDKを使用してメディアファイルを中国 (深セン) または中国 (北京) リージョンにアップロードする場合は、aliyun-java-sdk-vod V2.16.11以降およびaliyun-java-sdk-core V4.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>
シナリオ1: オーディオまたはビデオファイルのアップロード
通常のオーディオまたはビデオファイル
ApsaraVideo VODでは、次のいずれかの方法でオーディオまたはビデオファイルをアップロードできます。
マルチパートアップロードを使用して、ローカルのオーディオまたはビデオファイルをアップロードします。 この方法を使用すると、再開可能なアップロードを有効にできます。 詳細については、サンプルコードの
testUploadVideo
関数をご参照ください。再開可能なアップロードが有効になっていない場合、アップロードジョブは最大3,000秒間実行できます。 この場合、アップロードできるファイルの最大サイズは、ネットワーク帯域幅とディスクの読み書き容量によって異なります。
再開可能なアップロードを有効にすると、最大48.8テラバイトのファイルをアップロードできます。
重要再開可能なアップロードを有効にすると、ApsaraVideo VODはアップロード中にアップロードの進行状況をローカルディスクファイルに書き込みます。 これはアップロード速度に影響します。 ファイルサイズに基づいて再開可能なアップロード機能を有効にすることができます。
ネットワークストリームをアップロードします。 この方法を使用して、ファイルのURLを使用してオンラインのオーディオまたはビデオファイルをアップロードできます。 この方法では、再開可能なアップロードがサポートされます。 最大48.8テラバイトのファイルをアップロードできます。 オンラインファイルをアップロードする前に、ファイルをローカルディスクにダウンロードする必要があります。 ローカルディスクに十分な容量があることを確認してください。 詳細については、サンプルコードの
testUploadURLStream
関数をご参照ください。ファイルストリームをアップロードします。 この方法を使用して、指定したローカルファイルをアップロードできます。 この方法では、再開可能なアップロードはサポートされません。 最大5 GBのファイルをアップロードできます。 詳細については、サンプルコードの
testUploadFileStream
関数をご参照ください。ストリーミングアップロードを使用します。 この方法を使用して、ファイルストリームやネットワークストリームなどの指定されたストリームをアップロードできます。 この方法では、再開可能なアップロードはサポートされません。 最大5 GBのファイルをアップロードできます。 詳細については、次のサンプルコードの
testUploadStream
関数をご参照ください。
サンプルコードを使用する場合は、対応するクラスをインポートする必要があります。 コードの実行時に関連する依存関係が見つからない場合は、「トラブルシューティング」をご参照ください。
サンプルコードを表示する
public class UploadVideoDemo {
// Required. Enter the AccessKey pair of your Alibaba Cloud account.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
public static void main(String[] args) {
// Upload a video file.
// Required. Specify the title of the file.
String title = "Test";
// When you upload a local file or a file stream, set the file name to the absolute path of the file, such as /User/sample/File name.mp4. The file name is required.
// When you upload an online file, set the file name to the name of the source file, such as File name.mp4. The file name is required.
// When you use streaming upload, set the file name to the name of the source file, such as File name.mp4. The file name is required.
// The name of each file that you upload must contain a file name extension.
String fileName = "/Users/test/video/test.mp4";
// Upload a local file.
testUploadVideo(accessKeyId, accessKeySecret, title, fileName);
// Specify the URL of the online file that you want to upload.
String url = "http://test.aliyun.com/video/test.mp4";
// Upload a network stream.
// If the URL does not contain a file name extension, specify a file name extension.
String fileExtension = "mp4";
testUploadURLStream(accessKeyId, accessKeySecret, title, url, fileExtension);
// Upload a file stream.
testUploadFileStream(accessKeyId, accessKeySecret, title, fileName);
// Use streaming upload to upload a file stream or a network stream.
InputStream inputStream = null;
// Upload a file stream.
try {
inputStream = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Upload a network stream.
try {
inputStream = new URL(url).openStream();
} catch (IOException e) {
e.printStackTrace();
}
testUploadStream(accessKeyId, accessKeySecret, title, fileName, inputStream);
}
/**
* Specify the API operation that is used to upload local files.
*
* @param accessKeyId
* @param accessKeySecret
* @param title
* @param fileName
*/
private static void testUploadVideo(String accessKeyId, String accessKeySecret, String title, String fileName) {
UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
/* Specify the size of each part in multipart upload. Default value: 2. Unit: MB. */
request.setPartSize(2 * 1024 * 1024L);
/* Specify the number of concurrent threads for multipart upload. The default value is 1. Concurrent threads consume the CPU resources of the server. You can specify a value based on your server load. */
request.setTaskNum(1);
/* Specify whether to enable resumable upload. By default, resumable upload is disabled. If the upload is paused due to network disconnections or program crashes, you can resend an upload request to resume the upload. Resumable upload is suitable for large files that cannot be completely uploaded within a timeout period of 3,000 seconds.
Note: After you enable resumable upload, the upload progress is written to a local disk file during the upload. This affects the upload speed. Specify whether to enable resumable upload based on your business requirements. */
//request.setEnableCheckpoint(false);
/* Specify the timeout period of OSS slow requests for each part. If the system takes longer than the specified timeout period to upload a part, a debug log is generated. You can adjust the threshold to prevent debug log generation. The default timeout period is 300,000 milliseconds.*/
//request.setSlowRequestsThreshold(300000L);
/* Specify the timeout period of slow requests for each part. The default timeout period is 300 seconds. */
//request.setSlowRequestsThreshold(300000L);
/* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
//request.setIsShowWaterMark(true);
/* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
//request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
/* Optional. Specify the category ID of the video. */
//request.setCateId(0);
/* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the description of the video. */
// request.setDescription("Video description");
/* Optional. Specify the thumbnail of the video. */
//request.setCoverURL("http://cover.example.com/image_01.jpg");
/* Optional. Specify the ID of the template group that is used for the video. */
//request.setTemplateGroupId("8c4792cbc8694e7084fd5330e5****");
/* Optional. Specify the ID of the workflow. */
//request.setWorkflowId("d4430d07361f0*be1339577859b0****");
/* Optional. Specify the storage location. */
//request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
/* Enable the default callback for the upload progress. */
//request.setPrintProgress(false);
/* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
/* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
//request.setProgressListener(new PutObjectProgressListener());
/* Specify the class that is used to generate the Security Token Service (STS) information. */
// request.setVoDRefreshSTSTokenListener(new RefreshSTSTokenImpl());
/* Specify the ID of the application. */
//request.setAppId("app-100****");
/* Specify the access region of ApsaraVideo VOD. */
//request.setApiRegionId("cn-shanghai");
/* Specify the region in which the ECS instance is deployed. */
// request.setEcsRegionId("cn-shanghai");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadVideoResponse response = uploader.uploadVideo(request);
System.out.print("RequestId=" + response.getRequestId() + "\n"); // Specify the ID of the request that is sent to ApsaraVideo VOD.
if (response.isSuccess()) {
System.out.print("VideoId=" + response.getVideoId() + "\n");
} else {
/* If the callback URL that you specify is invalid, video upload is not affected. The video ID is returned with the error code. If the video ID is empty, the upload fails. Analyze the cause based on the returned error code. */
System.out.print("VideoId=" + response.getVideoId() + "\n");
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
/**
* Use URLs to upload online files. Resumable upload is supported. You can upload a file of up to 48.8 TB in size.
* Before you upload online files, you must download the files to a local disk. Make sure that the local disk has sufficient space.
* If the URL that you specify does not contain a file name extension, specify the fileExtension parameter.
* @param accessKeyId
* @param accessKeySecret
* @param title
* @param fileExtension
* @param url
*/
private static void testUploadURLStream(String accessKeyId, String accessKeySecret, String title, String url, String fileExtension) {
UploadURLStreamRequest request = new UploadURLStreamRequest(accessKeyId, accessKeySecret, title, url);
/* Specify the file name extension. */
request.setFileExtension(fileExtension);
/* Specify the timeout period of the connection that is established to download online files. Unit: milliseconds. The value 0 indicates no limit. */
request.setDownloadConnectTimeout(1000);
/* Specify the timeout period for reading online files. Unit: milliseconds. The value 0 indicates no limit. */
request.setDownloadReadTimeout(0);
/* Specify a local directory to store online files. */
request.setLocalDownloadFilePath("/Users/download");
/* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
//request.setShowWaterMark(true);
/* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
//request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
/* Optional. Specify the category ID of the video. */
//request.setCateId(0);
/* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the description of the video. */
// request.setDescription("Video description");
/* Optional. Specify the thumbnail of the video. */
//request.setCoverURL("http://cover.example.com/image_01.jpg");
/* Optional. Specify the ID of the template group that is used for the video. */
//request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
/* Optional. Specify the ID of the workflow. */
//request.setWorkflowId("d4430d07361f0*be1339577859b0****");
/* Optional. Specify the storage location. */
//request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
/* Enable the default callback for the upload progress. */
//request.setPrintProgress(true);
/* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
/* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
//request.setProgressListener(new PutObjectProgressListener());
/* Specify the ID of the application. */
//request.setAppId("app-100****");
/* Specify the access region of ApsaraVideo VOD. */
//request.setApiRegionId("cn-shanghai");
/* Specify the region in which the ECS instance is deployed. */
// request.setEcsRegionId("cn-shanghai");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadURLStreamResponse response = uploader.uploadURLStream(request);
System.out.print("RequestId=" + response.getRequestId() + "\n"); // Specify the ID of the request that is sent to ApsaraVideo VOD.
if (response.isSuccess()) {
System.out.print("VideoId=" + response.getVideoId() + "\n");
} else {
/* If the callback URL that you specify is invalid, video upload is not affected. The video ID is returned with the error code. If the video ID is empty, the upload fails. Analyze the cause based on the returned error code. */
System.out.print("VideoId=" + response.getVideoId() + "\n");
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
/**
* Specify the API operation that is used to upload a file stream.
*
* @param accessKeyId
* @param accessKeySecret
* @param title
* @param fileName
*/
private static void testUploadFileStream(String accessKeyId, String accessKeySecret, String title, String fileName) {
UploadFileStreamRequest request = new UploadFileStreamRequest(accessKeyId, accessKeySecret, title, fileName);
/* Optional. Specify whether to use the default watermark based on the configuration of the template group. */
//request.setShowWaterMark(true);
/* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
//request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
/* Optional. Specify the category ID of the video. */
//request.setCateId(0);
/* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the description of the video. */
// request.setDescription("Video description");
/* Optional. Specify the thumbnail of the video. */
//request.setCoverURL("http://cover.example.com/image_01.jpg");
/* Optional. Specify the ID of the template group that is used for the video. */
//request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
/* Optional. Specify the ID of the workflow. */
//request.setWorkflowId("d4430d07361f0*be1339577859b0****");
/* Optional. Specify the storage location. */
//request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
/* Enable the default callback for the upload progress. */
//request.setPrintProgress(true);
/* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
/* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
//request.setProgressListener(new PutObjectProgressListener());
/* Specify the ID of the application. */
//request.setAppId("app-100****");
/* Specify the access region of ApsaraVideo VOD. */
//request.setApiRegionId("cn-shanghai");
/* Specify the region in which the ECS instance is deployed. */
// request.setEcsRegionId("cn-shanghai");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadFileStreamResponse response = uploader.uploadFileStream(request);
System.out.print("RequestId=" + response.getRequestId() + "\n"); // Specify the ID of the request that is sent to ApsaraVideo VOD.
if (response.isSuccess()) {
System.out.print("VideoId=" + response.getVideoId() + "\n");
} else {
/* If the callback URL that you specify is invalid, video upload is not affected. The video ID is returned with the error code. If the video ID is empty, the upload fails. Analyze the cause based on the returned error code. */
System.out.print("VideoId=" + response.getVideoId() + "\n");
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
/**
* Specify the API operation that is used for streaming upload.
*
* @param accessKeyId
* @param accessKeySecret
* @param title
* @param fileName
* @param inputStream
*/
private static void testUploadStream(String accessKeyId, String accessKeySecret, String title, String fileName, InputStream inputStream) {
UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
/* Optional. Specify whether to use the default watermark based on the configuration of the template group. */
//request.setShowWaterMark(true);
/* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
//request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
/* Optional. Specify the category ID of the video. */
//request.setCateId(0);
/* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the description of the video. */
// request.setDescription("Video description");
/* Optional. Specify the thumbnail of the video. */
//request.setCoverURL("http://cover.example.com/image_01.jpg");
/* Optional. Specify the ID of the template group that is used for the video. */
//request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
/* Optional. Specify the ID of the workflow. */
//request.setWorkflowId("d4430d07361f0*be1339577859b0****");
/* Optional. Specify the storage location. */
//request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
/* Enable the default callback for the upload progress. */
// request.setPrintProgress(true);
/* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
/* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
// request.setProgressListener(new PutObjectProgressListener());
/* Specify the ID of the application. */
//request.setAppId("app-100****");
/* Specify the access region of ApsaraVideo VOD. */
//request.setApiRegionId("cn-shanghai");
/* Specify the region in which the ECS instance is deployed. */
// request.setEcsRegionId("cn-shanghai");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadStreamResponse response = uploader.uploadStream(request);
System.out.print("RequestId=" + response.getRequestId() + "\n"); // Specify the ID of the request that is sent to ApsaraVideo VOD.
if (response.isSuccess()) {
System.out.print("VideoId=" + response.getVideoId() + "\n");
} else { // If the callback URL that you specify is invalid, video upload is not affected. The video ID and an error code are returned. If the upload failure is not caused by an invalid callback URL, the ID of the video is empty. Identify the cause of the error based on the returned error code.
System.out.print("VideoId=" + response.getVideoId() + "\n");
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
}
M3U8ファイル
サンプルコードを表示する
public class UploadVideoDemo {
// Required. Enter the AccessKey pair of your Alibaba Cloud account.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
public static void main(String[] args) {
// Upload an M3U8 file.
// Upload a local M3U8 audio or video file.
testUploadLocalM3u8(accessKeyId, accessKeySecret);
// Upload an online M3U8 audio or video file.
testUploadWebM3u8(accessKeyId, accessKeySecret);
}
/**
* Upload a local M3U8 audio or video file to ApsaraVideo VOD. By default, the M3U8 file and the .ts parts are stored in the same directory. If you leave the sliceFilenames parameter empty, the path of the M3U8 file is parsed to obtain the paths of the .ts parts.
*
* @param request The request class for uploading local M3U8 files.
* m3u8Filename: the absolute path of the local M3U8 index file. The part information in the M3U8 file must contain relative paths and cannot contain URLs or absolute local paths.
* sliceFilenames: the absolute paths of the .ts parts. If you leave this parameter empty, ApsaraVideo VOD automatically parses the path of the M3U8 file specified by the m3u8Filename parameter.
*/
private static void testUploadLocalM3u8(String accessKeyId, String accessKeySecret) {
String title = "test_upload_local_m3u8";
String m3u8Filename = "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/cc38da35c7b24de0abe58619cdd7****-6479a12446b994719838e0307f****-ld.m3u8";
UploadLocalM3u8Request request = new UploadLocalM3u8Request(accessKeyId, accessKeySecret, title, m3u8Filename);
String[] sliceFilenames = new String[]{
"/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00001.ts",
"/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00002.ts",
"/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00003.ts",
"/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00004.ts",
"/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00005.ts"
};
// Optional. The list of .ts parts. If you leave this parameter empty, ApsaraVideo VOD automatically parses the m3u8FileURL parameter to obtain the paths of the .ts parts.
request.setSliceFilenames(sliceFilenames);
/* Specify the size of each part in multipart upload. Default value: 2. Unit: MB. */
request.setPartSize(2 * 1024 * 1024L);
/* Specify the number of concurrent threads for multipart upload. The default value is 1. Concurrent threads consume the CPU resources of the server. You can specify a value based on your server load. */
request.setTaskNum(1);
/* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
//request.setShowWaterMark(true);
/* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
//request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
/* Optional. Specify the category ID of the video. */
//request.setCateId(-1L);
/* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the description of the video. */
// request.setDescription("Video description");
/* Optional. Specify the thumbnail of the video. */
//request.setCoverURL("http://cover.sample.com/sample.jpg");
/* Optional. Specify the ID of the template group that is used for the video. */
//request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
/* Optional. Specify the ID of the workflow. */
//request.setWorkflowId("d4430d07361f0*be1339577859b0****");
/* Optional. Specify the storage location. */
//request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
/* Specify the ID of the application. */
// request.setAppId("app-1000000");
/* Specify the access region of ApsaraVideo VOD. */
// request.setApiRegionId("cn-shanghai");
/* Specify the region in which the ECS instance is deployed. */
// request.setEcsRegionId("cn-shanghai");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadM3u8FileImpl uploadM3u8File = new UploadM3u8FileImpl();
UploadLocalM3u8Response uploadLocalM3u8Response = uploadM3u8File.uploadLocalM3u8(request);
System.out.println("code = " + uploadLocalM3u8Response.getCode());
System.out.println("message = " + uploadLocalM3u8Response.getMessage());
System.out.println("videoId = " + uploadLocalM3u8Response.getVideoId());
System.out.println("requestId = " + uploadLocalM3u8Response.getRequestId());
}
/**
* Upload an online M3U8 audio or video file to ApsaraVideo VOD. Before you upload online M3U8 audio or video files, you must download the files to a local disk. Make sure that the local disk has sufficient space.
*
* @param request The request class for uploading online M3U8 files.
* m3u8FileURL: the URL of the online M3U8 index file. The part information in the M3U8 file must contain relative paths and cannot contain URLs or absolute local paths.
* sliceFileURLs: the URLs of the .ts parts. You must manually assemble the URLs.
*/
private static void testUploadWebM3u8(String accessKeyId, String accessKeySecret) {
String title = "test_upload_web_m3u8";
String m3u8FileURL = "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-538087dcf2c201c31ce4324bf76af69****.m3u8";
UploadWebM3u8Request request = new UploadWebM3u8Request(accessKeyId, accessKeySecret, title, m3u8FileURL);
String[] sliceFileURLs = new String[]{
"http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
"http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
"http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
"http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
"http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts"
};
// Optional. The list of .ts parts. If you leave this parameter empty, ApsaraVideo VOD automatically parses the m3u8FileURL parameter to obtain the URLs of .ts parts.
request.setSliceFileURLs(sliceFileURLs);
/* The custom temporary directory in which downloaded files are stored. If you leave this parameter empty, the downloaded files are stored in the directory in which your application resides. */
// request.setGlobalLocalFilePath("/User/download/");
/* Specify the size of each part in multipart upload. Default value: 2. Unit: MB. */
request.setPartSize(2 * 1024 * 1024L);
/* Specify the number of concurrent threads for multipart upload. The default value is 1. Concurrent threads consume the CPU resources of the server. You can specify a value based on your server load. */
request.setTaskNum(1);
/* Optional. Specify whether to display the watermark. When you specify the ID of the template group, specify whether to display the watermark based on the configuration of the template group. */
//request.setShowWaterMark(true);
/* Optional. Configure callback and upload acceleration settings. Specify custom extended configurations in the Extend field, callback configurations in the MessageCallback field, and upload acceleration configurations in the AccelerateConfig field. You must apply to enable the upload acceleration feature before you use the feature. */
//request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
/* Optional. Specify the category ID of the video. */
//request.setCateId(-1L);
/* Optional. Specify the tags of the video. Separate multiple tags with commas (,). */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the description of the video. */
// request.setDescription("Video description");
/* Optional. Specify the thumbnail of the video. */
//request.setCoverURL("http://cover.example.com/sample.jpg");
/* Optional. Specify the ID of the template group that is used for the video. */
//request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
/* Optional. Specify the ID of the workflow. */
//request.setWorkflowId("d4430d07361f0*be1339577859b0****");
/* Optional. Specify the storage location. */
//request.setStorageLocation("in-2017032321****-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
/* Specify the ID of the application. */
//request.setAppId("app-100****");
/* Specify the access region of ApsaraVideo VOD. */
//request.setApiRegionId("cn-shanghai");
/* Specify the region in which the ECS instance is deployed. */
// request.setEcsRegionId("cn-shanghai");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadM3u8FileImpl uploadM3u8File = new UploadM3u8FileImpl();
UploadWebM3u8Response uploadWebM3u8Response = uploadM3u8File.uploadWebM3u8(request);
System.out.println("code = " + uploadWebM3u8Response.getCode());
System.out.println("message = " + uploadWebM3u8Response.getMessage());
System.out.println("videoId = " + uploadWebM3u8Response.getVideoId());
System.out.println("requestId = " + uploadWebM3u8Response.getRequestId());
}
}
シナリオ2: 画像のアップロード
サンプルコードを表示する
public class UploadImageDemo {
// Required. Enter the AccessKey pair of your Alibaba Cloud account.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
public static void main(String[] args) {
// Upload an image.
// Upload a local image.
testUploadImageLocalFile(accessKeyId, accessKeySecret);
// Use streaming upload to upload a file stream or a network stream as an image.
testUploadImageStream(accessKeyId, accessKeySecret);
}
/**
* Specify the API operation that is used to upload local images.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadImageLocalFile(String accessKeyId, String accessKeySecret) {
/* Required. Specify the type of the image. Valid values: default, cover, and watermark. */
String imageType = "cover";
UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
request.setImageType("cover");
/* Optional. Specify the file name extension of the image. Valid values: png, jpg, and jpeg. */
//request.setImageExt("png");
/* Optional. Specify the title of the image. The title cannot exceed 128 bytes in length and must be in UTF-8. */
//request.setTitle("Image title");
/* Optional. Specify the tags of the image. A tag can be up to 32 bytes in length. You can enter up to 16 tags. Separate multiple tags with commas (,). Encode the tags in UTF-8. */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the storage location. */
//request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
/* Optional. In streaming upload, the InputStream parameter is required, and the fileName parameter is optional. Set the fileName parameter to the name of the source file. The file name must contain an extension, such as .png. */
String fileName = "/Users/demo/png/test.png";
request.setFileName(fileName);
/* Enable the default callback for the upload progress. */
//request.setPrintProgress(false);
/* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
/* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
// request.setProgressListener(new PutObjectProgressListener());
/* Specify the ID of the application. */
//request.setAppId("app-100****");
/* Specify the access region of ApsaraVideo VOD. */
//request.setApiRegionId("cn-shanghai");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadImageImpl uploadImage = new UploadImageImpl();
UploadImageResponse response = uploadImage.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("ImageId=" + response.getImageId() + "\n");
System.out.print("ImageURL=" + response.getImageURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
/**
* Specify the API operation that is used to upload a file stream or a network stream as an image.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadImageStream(String accessKeyId, String accessKeySecret) {
/* Required. Specify the type of the image. Valid values: default, cover, and watermark. */
String imageType = "cover";
UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
/* Optional. Specify the file name extension of the image. Valid values: png, jpg, and jpeg. */
//request.setImageExt("png");
/* Optional. Specify the title of the image. The title cannot exceed 128 bytes in length and must be in UTF-8. */
//request.setTitle("Image title");
/* Optional. Specify the tags of the image. A tag can be up to 32 bytes in length. You can enter up to 16 tags. Separate multiple tags with commas (,). Encode the tags in UTF-8. */
// request.setTags("tag 1,tag 2");
/* Optional. Specify the storage location. */
//request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
/* Optional. In streaming upload, the InputStream parameter is required, and the fileName parameter is optional. Set the fileName parameter to the name of the source file. The file name must contain an extension, such as .png. */
//request.setFileName("Test file name.png");
/* Enable the default callback for the upload progress. */
// request.setPrintProgress(true);
/* Specify a custom callback for the upload progress. The callback must inherit VoDProgressListener. */
/* By default, the custom callback for the upload progress feature is disabled. If you enable this feature, the system returns upload details in the logs during the upload. Disable this feature if you do not need to receive upload details. */
// request.setProgressListener(new PutObjectProgressListener());
/* Specify the ID of the application. */
//request.setAppId("app-1000000");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
// Upload a file stream.
// InputStream fileStream = getFileStream(request.getFileName());
// if (fileStream != null) {
// request.setInputStream(fileStream);
// }
// Upload a network stream.
String url = "http://test.aliyun.com/image/default/test.png";
InputStream urlStream = getUrlStream(url);
if (urlStream != null) {
request.setInputStream(urlStream);
}
// Start the upload.
UploadImageImpl uploadImage = new UploadImageImpl();
UploadImageResponse response = uploadImage.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("ImageId=" + response.getImageId() + "\n");
System.out.print("ImageURL=" + response.getImageURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
private static InputStream getFileStream(String fileName) {
try {
return new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static InputStream getUrlStream(String url) {
try {
return new URL(url).openStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
シナリオ3: 補助メディア資産のアップロード
サンプルコードを表示する
public class UploadAttachedMediaDemo {
// Required. Enter the AccessKey pair of your Alibaba Cloud account.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
public static void main(String[] args) {
// Upload an auxiliary media asset.
// Upload a local auxiliary media asset.
testUploadAttachedMediaLocalFile(accessKeyId, accessKeySecret);
// Use streaming upload to upload a file stream or a network stream as an auxiliary media asset.
testUploadAttachedMediaStream(accessKeyId, accessKeySecret);
}
/**
* Specify the API operation that is used to upload a local auxiliary media asset.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadAttachedMediaLocalFile(String accessKeyId, String accessKeySecret) {
/* Specify the business type. */
String businessType = "watermark";
/* Specify the file name extension. */
String mediaExt = "png";
String filename = "/Users/demo/png/test.png";
UploadAttachedMediaRequest request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
request.setFileName(filename);
/* Specify the title. */
request.setTitle("test_attached_media");
/* Specify the category ID. */
request.setCateId(-1L);
/* Optional. Specify the tags. Separate multiple tags with commas (,). */
request.setTags("tag1,tag2");
/* Optional. Specify the description. */
request.setDescription("test_desc");
/* Optional. Specify the storage location. */
request.setStorageLocation("out-20170323225118266-5l3hs5****.oss-cn-shanghai.aliyuncs.com");
/* Specify the access region of ApsaraVideo VOD. */
request.setApiRegionId("cn-shanghai");
/* Specify the ID of the application. */
//request.setAppId("app-1000000");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();
UploadAttachedMediaResponse response = uploader.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("MediaId=" + response.getMediaId() + "\n");
System.out.print("MediaURL=" + response.getMediaURL() + "\n");
System.out.print("FileURL=" + response.getFileURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
/**
* Specify the API operation that is used to upload a file stream or a network stream as an auxiliary media asset.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadAttachedMediaStream(String accessKeyId, String accessKeySecret) {
/* Specify the business type. */
String businessType = "watermark";
/* Specify the file name extension. */
String mediaExt = "png";
String filename = "http://test.aliyun.com/test.png";
UploadAttachedMediaRequest request;
// Upload a file stream.
InputStream fileStream = getFileStream(filename);
request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
request.setInputStream(fileStream);
// Upload a network stream.
// String url = "http://test.aliyun.com/image//test.png";
// InputStream urlStream = getUrlStream(url);
// request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
// request.setInputStream(urlStream);
/* Specify the title. */
request.setTitle("test_attached_media");
/* Specify the category ID. */
request.setCateId(-1L);
/* Optional. Specify the tags. Separate multiple tags with commas (,). */
request.setTags("tag1,tag2");
/* Optional. Specify the description. */
request.setDescription("test_desc");
/* Optional. Specify the storage location. */
request.setStorageLocation("out-20170323225118266-5l3****wa.oss-cn-shanghai.aliyuncs.com");
/* Specify the access region of ApsaraVideo VOD. */
request.setApiRegionId("cn-shanghai");
/* Specify the ID of the application. */
// request.setAppId("app-1000000");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. Specify the address of the proxy server. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. Specify the port that is used to connect to the proxy server. */
//ossConfig.setProxyPort(-1);
/* Specify the protocol that is used to access OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* Specify the User-Agent field in the HTTP headers. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* Specify the username that is used to log on to the proxy server. The username is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* Specify the password that is used to log on to the proxy server. The password is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
// Start the upload.
UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();
UploadAttachedMediaResponse response = uploader.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("MediaId=" + response.getMediaId() + "\n");
System.out.print("MediaURL=" + response.getMediaURL() + "\n");
System.out.print("FileURL=" + response.getFileURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
private static InputStream getFileStream(String fileName) {
try {
return new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static InputStream getUrlStream(String url) {
try {
return new URL(url).openStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
高度な機能
アップロードプログレスバーのサンプルコード
サンプルディレクトリの
PutObjectProgressListener.java
ファイルは、アップロードの進行状況のコールバック関数のサンプルコードです。クラスはVoDProgressListenerクラスを継承する必要があります。 ProgressEventは、ファイルをOSSにアップロードするときにアップロードの進行状況を通知するために生成されるイベントを示します。 さまざまなイベント通知用にカスタムビジネス処理ロジックを作成できます。
次のサンプルコードに例を示します。
サンプルコードを表示する
/** * Specify the class of callbacks for the upload progress. * The callback takes effect only when you enable the callback for the upload progress. * A callback is triggered when the OSS multipart upload succeeds or fails. You can handle event callbacks based on the business processing logic. * After the video or audio information is created, the value of the videoId parameter in the callback for the upload progress is the video ID that is generated in the current upload. You can manage video and audio files based on the video IDs. * After the image information is created, the value of the ImageId parameter in the callback for the upload progress is the image ID that is generated in the current upload. You can manage images based on the image IDs. */ public class PutObjectProgressListener implements VoDProgressListener { /** * The number of bytes that are uploaded to OSS. */ private long bytesWritten = 0; /** * The total size of the source file. Unit: bytes. */ private long totalBytes = -1; /** * Indicates whether the current upload is successful. */ private boolean succeed = false; /** * The ID of the video. */ private String videoId; /** * The ID of the image. */ private String imageId; public void progressChanged(ProgressEvent progressEvent) { long bytes = progressEvent.getBytes(); ProgressEventType eventType = progressEvent.getEventType(); switch (eventType) { // The event notification indicates that the upload starts. case TRANSFER_STARTED_EVENT: if (videoId != null) { System.out.println("Start to upload videoId "+videoId+"......"); } if (imageId != null) { System.out.println("Start to upload imageId "+imageId+"......"); } break; // The event notification indicates the total size of the file that you want to upload. Unit: bytes. The event is supported only in the upload of local files. case REQUEST_CONTENT_LENGTH_EVENT: this.totalBytes = bytes; System.out.println(this.totalBytes + "bytes in total will be uploaded to OSS."); break; // The event notification indicates the size of uploaded files. Unit: bytes. case REQUEST_BYTE_TRANSFER_EVENT: this.bytesWritten += bytes; if (this.totalBytes != -1) { int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes); System.out.println(bytes+" bytes have been written at this time, upload progress: "+ percent +"%(" + this.bytesWritten + "/" + this.totalBytes + ")"); } else { System.out.println(bytes + " bytes have been written at this time, upload sub total : " + "(" + this.bytesWritten + ")"); } break; // The event notification indicates that all files are uploaded. case TRANSFER_COMPLETED_EVENT: this.succeed = true; if (videoId != null) { System.out.println("Succeed to upload videoId " + videoId + " , " + this.bytesWritten + " bytes have been transferred in total."); } if (imageId != null) { System.out.println("Succeed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred in total."); } break; // The event notification indicates that the upload fails. case TRANSFER_FAILED_EVENT: if (videoId != null) { System.out.println("Failed to upload videoId " + videoId + " , " + this.bytesWritten + " bytes have been transferred."); } if (imageId != null) { System.out.println("Failed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred."); } break; default: break; } } public boolean isSucceed() { return succeed; } public void onVidReady(String videoId) { setVideoId(videoId); } public void onImageIdReady(String imageId) { setImageId(imageId); } public String getVideoId() { return videoId; } public void setVideoId(String videoId) { this.videoId = videoId; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } }
一時トークンを更新するためのサンプルコード
サンプルディレクトリの
RefreshSTSTokenImpl.java
ファイルは、一時トークンを更新するために使用できるサンプルコードです。サンプルコード:
サンプルコードを表示する
/** * @author vod * Specify the implementation class that is used to generate STS information. * @date 2019/6/5 */ public class RefreshSTSTokenImpl implements VoDRefreshSTSTokenListener { public STSTokenDTO onRefreshSTSToken() { STSTokenDTO stsTokenDTO = new STSTokenDTO(); stsTokenDTO.setAccessKeyId("<your sts AccessKeyId>"); stsTokenDTO.setAccessKeySecret("<your sts AccessKeySecret>"); stsTokenDTO.setSecurityToken("<your sts SecurityToken>"); return stsTokenDTO; } }
よくある質問
問題1: 開発環境の違いにより、SDKが関連する依存関係を見つけることができない場合があります。 ほとんどの場合、この問題はIntelliJ IDEA開発環境でのコンパイルによって発生します。 必要なリソースパッケージをインポートしている場合は、次の方法で問題を解決できます。
Mavenプロジェクトで、右上隅の [Maven] をクリックします。 次に、mアイコンをクリックし、
mvn idea:module
と入力してリソースをリロードします。上部のナビゲーションバーで、[ビルド] > [プロジェクトの再構築] を選択してプロジェクトを編集します。
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>