Use o SDK de upload do lado do servidor para Java para enviar arquivos de áudio, vídeo, imagem e mídias auxiliares ao ApsaraVideo VOD.
Visão geral
O SDK de upload para Java segue o processo de upload do ApsaraVideo VOD. As etapas básicas são:
Cumpra os Pré-requisitos.
-
Implemente a lógica de upload (principalmente a configuração do envio).
Arquivos de áudio e vídeo: Cenário 1: Envio de arquivos de áudio e vídeo.
Imagens: Cenário 2: Envio de imagens.
Recursos de mídia auxiliar: Cenário 3: Envio de recursos de mídia auxiliar.
Pré-requisitos
O ApsaraVideo VOD deve estar ativado. Para mais informações, consulte Ativar o ApsaraVideo VOD.
Configure as definições de sistema necessárias para o upload, incluindo o caminho de armazenamento na região especificada e as configurações de callback. Para mais detalhes, consulte Gerenciar buckets de armazenamento e Configurar callbacks.
Crie um usuário RAM para acessar o ApsaraVideo VOD. Para evitar riscos de segurança causados pelo vazamento do par AccessKey da sua conta Alibaba Cloud, recomendamos criar um usuário RAM e conceder a ele as permissões necessárias para acessar o serviço. Em seguida, use o par AccessKey desse usuário RAM para acessar o ApsaraVideo VOD. Para mais informações, consulte Criar um usuário RAM e conceder permissões.
-
Configure as variáveis de ambiente ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET. Para mais informações, consulte Configurar variáveis de ambiente no Linux, macOS e Windows.
ImportanteO par AccessKey de uma conta Alibaba Cloud tem permissões em todas as operações de API. Use o par AccessKey de um usuário RAM para chamar operações de API ou executar tarefas rotineiras de O&M.
Não codifique rigidamente seu AccessKey ID e AccessKey Secret no código do projeto. Se houver vazamento, todos os recursos da sua conta ficarão comprometidos.
(Opcional) Crie uma função para o usuário RAM e conceda as permissões necessárias para acessar o ApsaraVideo VOD, caso deseje acessar o serviço por meio do Security Token Service (STS). Para mais informações, consulte Obter um token STS.
Integrar o SDK de upload para Java
Este exemplo usa Java 1.8+ e o SDK de upload para Java 1.4.15. Os passos podem variar conforme a versão. O SDK requer importação manual do JAR — não há suporte para integração direta via dependência. Consulte Solução de problemas.
-
Baixe o SDK de upload para Java e o código de exemplo.
Versão do SDK: 1.4.15
Data de atualização: 2022-11-03
Endereço para download: Código-fonte do SDK V1.4.15 e demo
-
Descompacte o pacote baixado.
Após extrair o arquivo VODUploadDemo-java-1.4.15.zip, você obterá as seguintes pastas:
lib: Pacotes JAR necessários para o SDK de upload.sample: Código de exemplo do SDK de upload.
-
Importe os pacotes JAR.
Eclipse: Clique com o botão direito no projeto, selecione Properties > Java Build Path > Add JARs, navegue até a pasta extraída VODUploadDemo-java-1.4.15 e adicione todos os arquivos jar do diretório
lib.IntelliJ IDEA: Selecione File > Project Structure > Modules, clique em Dependencies à direita, clique em + e depois em JARs or directories. Navegue até o diretório extraído VODUploadDemo-java-1.4.15 e adicione todos os arquivos jar do diretório
lib.
ImportanteApós importar os pacotes JAR, configure as dependências.
-
Adicione as dependências: Alibaba Cloud SDK for Java, OSS SDK, ApsaraVideo VOD server-side SDK e ApsaraVideo VOD upload SDK.
ImportanteTodas as dependências listadas são obrigatórias. A ausência de qualquer uma delas causa falha na integração.
Se usar o pacote JAR mais recente (aliyun-java-vod-upload-1.4.15.jar), garanta que a versão do aliyun-sdk-oss seja 3.9.0 ou superior e a versão do aliyun-java-sdk-vod seja 2.16.11 ou superior.
O ApsaraVideo VOD está disponível nas regiões China (Shanghai), China (Shenzhen) e China (Beijing). Para uploads destinados à China (Shenzhen) ou China (Beijing): o SDK de upload 1.4.14 ou anterior requer aliyun-java-sdk-vod 2.15.11+ e aliyun-java-sdk-core 4.4.5+; já o SDK de upload 1.4.15 ou posterior exige aliyun-java-sdk-vod 2.16.11+ e aliyun-java-sdk-core 4.4.5+.
Mostrar dependências
<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>
Cenário 1: Envio de arquivos de áudio e vídeo
Arquivos comuns de áudio e vídeo
O ApsaraVideo VOD oferece quatro métodos para enviar arquivos de áudio e vídeo:
-
Envio de arquivo local. Usa upload multipart com suporte a retomada. Exemplo:
testUploadVideo.Sem a retomada de upload, as tarefas executam por no máximo 3.000 segundos. O tamanho máximo do arquivo depende da largura de banda da rede e da E/S do disco.
-
Com a retomada de upload ativada, é possível enviar um único arquivo de até 48,8 TB.
ImportanteA retomada de upload grava o progresso em um arquivo local, o que pode afetar a velocidade de envio. Considere ativar esse recurso para arquivos grandes.
Envio de fluxo de rede via URL. Suporta retomada de upload para arquivos de até 48,8 TB. Baixa o arquivo localmente antes de enviar — garanta espaço suficiente em disco. Exemplo:
testUploadURLStream.Envio de fluxo de arquivo a partir de um arquivo local. Não suporta retomada. Tamanho máximo do arquivo: 5 GB. Exemplo:
testUploadFileStream.Envio de fluxo de entrada (fluxo de arquivo ou fluxo de rede). Não suporta retomada. Tamanho máximo do arquivo: 5 GB. Exemplo:
testUploadStream.
Ao usar o código de exemplo, importe manualmente as classes necessárias. Caso encontre erros de dependência ausente, verifique as Perguntas frequentes.
Código de exemplo
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");
}
}
}
Arquivos M3U8
Código de exemplo
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());
}
}
Aceleração de upload
Para arquivos grandes (GBs ou TBs) ou uploads entre regiões (por exemplo, da China continental para a região de armazenamento de Singapura), ative a aceleração de upload. Consulte Ativar aceleração de upload. Após ativá-la, adicione o par chave-valor AccelerateConfig ao objeto UserData na configuração de upload. Crie o objeto UserData caso ele não exista. Exemplo:
request.setUserData("{\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
Parâmetros
|
Parâmetro |
Tipo |
Descrição |
|
Type |
String |
Serviço para o qual ativar a aceleração de upload. Defina este valor como |
|
Domain |
String |
Endpoint acelerado do seu bucket. O protocolo padrão é HTTPS. Nota
Use o endpoint acelerado fornecido após ativar este recurso, como |
Cenário 2: Envio de imagens
Mostrar código de exemplo
public class UploadImageDemo {
// Required. The AccessKey pair of your Alibaba Cloud account.
// An Alibaba Cloud account's AccessKey pair can access all APIs. We recommend that you use a RAM user for API access or routine operations.
// We strongly recommend that you do not hard-code your AccessKey ID and AccessKey secret in your project code. This can leak your credentials and compromise the security of all resources in your account.
// This example obtains an AccessKey pair from environment variables. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
public static void main(String[] args) {
// Upload an image.
// 1. Upload an image from a local file.
testUploadImageLocalFile(accessKeyId, accessKeySecret);
// 2. Upload an image by using a file or network stream.
testUploadImageStream(accessKeyId, accessKeySecret);
}
/**
* Uploads an image from a local file.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadImageLocalFile(String accessKeyId, String accessKeySecret) {
/* Required. The type of the image. Valid values: default, cover, and watermark. */
String imageType = "cover";
UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
request.setImageType("cover");
/* Optional. The image file extension. Valid values: png, jpg, and jpeg. */
//request.setImageExt("png");
/* Optional. The image title. The title must be in UTF-8 and cannot exceed 128 bytes. */
//request.setTitle("Image title");
/* Optional. The image tags. You can add up to 16 tags, separated by commas (,). Each tag must be in UTF-8 and cannot exceed 32 bytes. */
//request.setTags("Tag1,Tag2");
/* Optional. The storage location. */
//request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
/* For streaming upload, the InputStream parameter is required. The fileName parameter (the name of the source file) is optional. Example: filename.png. */
String fileName = "/Users/demo/png/test.png";
request.setFileName(fileName);
/* Enables the default upload progress callback. */
//request.setPrintProgress(false);
/* Sets a custom upload progress callback. You must inherit from VoDProgressListener. */
/* This feature is disabled by default. If enabled, the server logs upload details during the upload process. Disable this feature if you do not need these logs. */
// request.setProgressListener(new PutObjectProgressListener());
/* Optional. The application ID. */
//request.setAppId("app-100****");
/* The region ID for the ApsaraVideo VOD access point. */
//request.setApiRegionId("cn-shanghai");
/* Optional. Configures a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* <Required> The proxy server's host address. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* <Required> The proxy server's port. */
//ossConfig.setProxyPort(-1);
/* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadImageImpl uploadImage = new UploadImageImpl();
UploadImageResponse response = uploadImage.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("ImageId=" + response.getImageId() + "\n");
System.out.print("ImageURL=" + response.getImageURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
/**
* Uploads an image from a stream. This method supports both file and network streams.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadImageStream(String accessKeyId, String accessKeySecret) {
/* Required. The type of the image. Valid values: default, cover, and watermark. */
String imageType = "cover";
UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
/* Optional. The image file extension. Valid values: png, jpg, and jpeg. */
//request.setImageExt("png");
/* Optional. The image title. The title must be in UTF-8 and cannot exceed 128 bytes. */
//request.setTitle("Image title");
/* Optional. The image tags. You can add up to 16 tags, separated by commas (,). Each tag must be in UTF-8 and cannot exceed 32 bytes. */
//request.setTags("Tag1,Tag2");
/* Optional. The storage location. */
//request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
/* For streaming upload, the InputStream parameter is required. The fileName parameter (the name of the source file) is optional. Example: filename.png. */
//request.setFileName("Test file name.png");
/* Enables the default upload progress callback. */
// request.setPrintProgress(true);
/* Sets a custom upload progress callback. You must inherit from VoDProgressListener. */
/* This feature is disabled by default. If enabled, the server logs upload details during the upload process. Disable this feature if you do not need these logs. */
// request.setProgressListener(new PutObjectProgressListener());
/* Optional. The application ID. */
//request.setAppId("app-1000000");
/* Optional. Configures a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* <Required> The proxy server's host address. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* <Required> The proxy server's port. */
//ossConfig.setProxyPort(-1);
/* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
// 1. Upload a file stream.
// InputStream fileStream = getFileStream(request.getFileName());
// if (fileStream != null) {
// request.setInputStream(fileStream);
// }
// 2. Upload a network stream.
String url = "http://test.aliyun.com/image/default/test.png";
InputStream urlStream = getUrlStream(url);
if (urlStream != null) {
request.setInputStream(urlStream);
}
// Start the image upload.
UploadImageImpl uploadImage = new UploadImageImpl();
UploadImageResponse response = uploadImage.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("ImageId=" + response.getImageId() + "\n");
System.out.print("ImageURL=" + response.getImageURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
private static InputStream getFileStream(String fileName) {
try {
return new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static InputStream getUrlStream(String url) {
try {
return new URL(url).openStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Cenário 3: Envio de recursos de mídia auxiliar
Código de exemplo
public class UploadAttachedMediaDemo {
// Required. The AccessKey pair of your account.
// An AccessKey pair for an Alibaba Cloud account grants full access to all API operations. We recommend using a RAM user for API access and routine O&M.
// To prevent leaks, do not hard-code your AccessKey ID and AccessKey Secret in your project. A leaked AccessKey pair can compromise the security of all resources in your account.
// This example retrieves an AccessKey pair from environment variables for identity verification. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
public static void main(String[] args) {
// Upload auxiliary media assets.
// Upload an auxiliary media asset from a local file.
testUploadAttachedMediaLocalFile(accessKeyId, accessKeySecret);
// Upload an auxiliary media asset by using streaming upload (file stream and network stream).
testUploadAttachedMediaStream(accessKeyId, accessKeySecret);
}
/**
* Uploads a local auxiliary media asset.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadAttachedMediaLocalFile(String accessKeyId, String accessKeySecret) {
/* The business type. */
String businessType = "watermark";
/* The file name extension. */
String mediaExt = "png";
String filename = "/Users/demo/png/test.png";
UploadAttachedMediaRequest request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
request.setFileName(filename);
/* The title. */
request.setTitle("test_attached_media");
/* The category ID. */
request.setCateId(-1L);
/* Optional. The tags. Separate multiple tags with commas. */
request.setTags("tag1,tag2");
/* Optional. The description. */
request.setDescription("test_desc");
/* Optional. The storage location. */
request.setStorageLocation("out-20170323225118266-5l3hs5****.oss-cn-shanghai.aliyuncs.com");
/* The access region of ApsaraVideo VOD. */
request.setApiRegionId("cn-shanghai");
/* The application ID. */
//request.setAppId("app-1000000");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. The proxy host. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. The proxy port. */
//ossConfig.setProxyPort(-1);
/* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();
UploadAttachedMediaResponse response = uploader.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("MediaId=" + response.getMediaId() + "\n");
System.out.print("MediaURL=" + response.getMediaURL() + "\n");
System.out.print("FileURL=" + response.getFileURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
/**
* Uploads an auxiliary media asset by using streaming upload. This method supports file streams and network streams.
*
* @param accessKeyId
* @param accessKeySecret
*/
private static void testUploadAttachedMediaStream(String accessKeyId, String accessKeySecret) {
/* The business type. */
String businessType = "watermark";
/* The file name extension. */
String mediaExt = "png";
String filename = "http://test.aliyun.com/test.png";
UploadAttachedMediaRequest request;
// 1. Upload from a file stream.
InputStream fileStream = getFileStream(filename);
request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
request.setInputStream(fileStream);
// 2. Upload from a network stream.
// String url = "http://test.aliyun.com/image//test.png";
// InputStream urlStream = getUrlStream(url);
// request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
// request.setInputStream(urlStream);
/* The title. */
request.setTitle("test_attached_media");
/* The category ID. */
request.setCateId(-1L);
/* Optional. The tags. Separate multiple tags with commas. */
request.setTags("tag1,tag2");
/* Optional. The description. */
request.setDescription("test_desc");
/* Optional. The storage location. */
request.setStorageLocation("out-20170323225118266-5l3****wa.oss-cn-shanghai.aliyuncs.com");
/* The access region of ApsaraVideo VOD. */
request.setApiRegionId("cn-shanghai");
/* The application ID. */
// request.setAppId("app-1000000");
/* Optional. Configure a proxy. */
//OSSConfig ossConfig = new OSSConfig();
/* Required. The proxy host. */
//ossConfig.setProxyHost("<yourProxyHost>");
/* Required. The proxy port. */
//ossConfig.setProxyPort(-1);
/* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
//ossConfig.setProtocol("HTTP");
/* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
//ossConfig.setUserAgent("<yourUserAgent>");
/* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyUsername("<yourProxyUserName>");
/* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
//ossConfig.setProxyPassword("<yourProxyPassword>");
//request.setOssConfig(ossConfig);
// Start the upload.
UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();
UploadAttachedMediaResponse response = uploader.upload(request);
System.out.print("RequestId=" + response.getRequestId() + "\n");
if (response.isSuccess()) {
System.out.print("MediaId=" + response.getMediaId() + "\n");
System.out.print("MediaURL=" + response.getMediaURL() + "\n");
System.out.print("FileURL=" + response.getFileURL() + "\n");
} else {
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
private static InputStream getFileStream(String fileName) {
try {
return new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static InputStream getUrlStream(String url) {
try {
return new URL(url).openStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Recursos avançados
-
Barra de progresso de upload
O arquivo
PutObjectProgressListener.javano diretóriosamplefornece uma implementação de callback para o progresso do upload.Essa classe implementa a interface
VoDProgressListener. Um objetoProgressEventrelata o progresso do envio de arquivos para o OSS, permitindo adicionar lógica personalizada para cada evento.O código a seguir apresenta um exemplo.
Mostrar código de exemplo
/** * An implementation of a listener for upload progress callbacks. * This callback is invoked only if you enable upload progress notifications. * A callback event is triggered when a multipart upload to OSS succeeds or fails. You can implement custom logic to handle the event. * When uploading an audio or video file, this callback provides the `videoId`, which you can use to manage the file. * When uploading an image, this callback provides the `imageId`, which you can use to manage the image. */ public class PutObjectProgressListener implements VoDProgressListener { /** * Number of bytes that have been successfully uploaded to OSS. */ private long bytesWritten = 0; /** * Total size of the source file in bytes. */ private long totalBytes = -1; /** * Indicates whether the upload completed successfully. */ private boolean succeed = false; /** * The video ID. */ private String videoId; /** * The image ID. */ private String imageId; public void progressChanged(ProgressEvent progressEvent) { long bytes = progressEvent.getBytes(); ProgressEventType eventType = progressEvent.getEventType(); switch (eventType) { // Indicates that the upload started. case TRANSFER_STARTED_EVENT: if (videoId != null) { System.out.println("Start to upload videoId "+videoId+"......"); } if (imageId != null) { System.out.println("Start to upload imageId "+imageId+"......"); } break; // Provides the total size of the file to be uploaded. This event is supported only for local file uploads. case REQUEST_CONTENT_LENGTH_EVENT: this.totalBytes = bytes; System.out.println(this.totalBytes + "bytes in total will be uploaded to OSS."); break; // Indicates the number of bytes that have been transferred. case REQUEST_BYTE_TRANSFER_EVENT: this.bytesWritten += bytes; if (this.totalBytes != -1) { int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes); System.out.println(bytes+" bytes have been written at this time, upload progress: "+ percent +"%(" + this.bytesWritten + "/" + this.totalBytes + ")"); } else { System.out.println(bytes + " bytes have been written at this time, upload sub total : " + "(" + this.bytesWritten + ")"); } break; // Indicates that the transfer is complete. case TRANSFER_COMPLETED_EVENT: this.succeed = true; if (videoId != null) { System.out.println("Succeed to upload videoId " + videoId + " , " + this.bytesWritten + " bytes have been transferred in total."); } if (imageId != null) { System.out.println("Succeed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred in total."); } break; // Indicates that the transfer failed. case TRANSFER_FAILED_EVENT: if (videoId != null) { System.out.println("Failed to upload videoId " + videoId + " , " + this.bytesWritten + " bytes have been transferred."); } if (imageId != null) { System.out.println("Failed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred."); } break; default: break; } } public boolean isSucceed() { return succeed; } public void onVidReady(String videoId) { setVideoId(videoId); } public void onImageIdReady(String imageId) { setImageId(imageId); } public String getVideoId() { return videoId; } public void setVideoId(String videoId) { this.videoId = videoId; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } } -
Atualizar um token temporário
O arquivo
RefreshSTSTokenImpl.javano diretóriosampledemonstra como atualizar um token temporário.O código a seguir apresenta um exemplo.
Mostrar código de exemplo
/** * @author vod * An implementation that retrieves a temporary token from Security Token Service (STS). * @date 2019/6/5 */ public class RefreshSTSTokenImpl implements VoDRefreshSTSTokenListener { public STSTokenDTO onRefreshSTSToken() { STSTokenDTO stsTokenDTO = new STSTokenDTO(); stsTokenDTO.setAccessKeyId("<Your STS AccessKeyId>"); stsTokenDTO.setAccessKeySecret("<Your STS AccessKeySecret>"); stsTokenDTO.setSecurityToken("<Your STS SecurityToken>"); return stsTokenDTO; } }
Perguntas frequentes
Problema 1: Erros de dependência ausente
No projeto Maven, clique em Maven à direita, clique no ícone m e insira
mvn idea:modulepara recarregar os recursos.Na barra de menu superior, selecione Build > Rebuild Project.
-
Copie o arquivo aliyun-java-vod-upload-1.4.15.jar para o diretório de recursos do projeto e adicione uma dependência Maven local:
<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>Exemplo de dependências Maven após adicionar a dependência local.
<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>