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");
}
}
}