Tous les produits
Search
Centre de documentation

ApsaraVideo VOD:Upload files with the Java SDK

Dernière mise à jour :Aug 10, 2026

Utilisez le SDK de téléversement côté serveur pour Java afin de téléverser des fichiers audio, vidéo, image et des ressources multimédias auxiliaires vers ApsaraVideo VOD.

Présentation

Le SDK de téléversement Java suit le processus de téléversement d'ApsaraVideo VOD. Les étapes de base sont les suivantes :

  1. Effectuez les opérations décrites dans la section Prérequis.

  2. Intégrez le SDK de téléversement Java.

  3. Mettez en œuvre la logique de téléversement (principalement la configuration du téléversement).

Prérequis

  • ApsaraVideo VOD est activé. Pour plus d'informations, consultez la rubrique Activer ApsaraVideo VOD.

  • Les paramètres système requis pour le téléversement, y compris le chemin de stockage dans la région spécifiée et les paramètres de rappel, sont configurés. Pour plus d'informations, consultez les rubriques Gérer les buckets de stockage et Configurer les rappels.

  • Un utilisateur RAM est créé et utilisé pour accéder à ApsaraVideo VOD. Afin de prévenir les risques de sécurité liés à la divulgation de la paire AccessKey de votre compte Alibaba Cloud, nous vous recommandons de créer un utilisateur RAM et de lui accorder les permissions nécessaires pour accéder à ApsaraVideo VOD. Vous pouvez ensuite utiliser la paire AccessKey de l'utilisateur RAM pour accéder à ApsaraVideo VOD. Pour plus d'informations, consultez la rubrique Créer un utilisateur RAM et accorder des permissions.

  • Configurez les variables d'environnement ALIBABA_CLOUD_ACCESS_KEY_ID et ALIBABA_CLOUD_ACCESS_KEY_SECRET. Pour plus d'informations, consultez la rubrique Configurer les variables d'environnement sous Linux, macOS et Windows.

    Important
    • Une paire AccessKey de compte Alibaba Cloud dispose des permissions sur toutes les opérations API. Utilisez la paire AccessKey d'un utilisateur RAM pour appeler des opérations API ou effectuer des tâches O&M courantes.

    • N'intégrez pas en dur votre ID AccessKey et votre secret AccessKey dans le code de votre projet. En cas de fuite, toutes les ressources de votre compte seraient compromises.

  • Facultatif. Un rôle est créé pour l'utilisateur RAM et ce rôle reçoit les permissions nécessaires pour accéder à ApsaraVideo VOD si vous souhaitez accéder à ApsaraVideo VOD via Security Token Service (STS). Pour plus d'informations, consultez la rubrique Obtenir un jeton STS.

Intégrer le SDK de téléversement pour Java

Remarque

Cet exemple utilise Java 1.8+ et le SDK de téléversement pour Java 1.4.15. Les étapes peuvent varier selon la version. Le SDK nécessite une importation manuelle des fichiers JAR ; l'intégration directe via dépendance n'est pas prise en charge. Consultez la section Dépannage.

  1. Téléchargez le SDK de téléversement pour Java et l'exemple de code.

  2. Décompressez le package téléchargé.

    Après extraction du fichier VODUploadDemo-java-1.4.15.zip, vous obtenez les dossiers suivants :

    • lib : packages JAR requis par le SDK de téléversement.

    • sample : exemple de code pour le SDK de téléversement.

  3. Importez les packages JAR.

    • Eclipse : cliquez avec le bouton droit sur votre projet, sélectionnez Properties > Java Build Path > Add JARs, accédez au dossier extrait VODUploadDemo-java-1.4.15 et ajoutez tous les fichiers jar du répertoire lib.

    • IntelliJ IDEA : sélectionnez File > Project Structure > Modules, cliquez sur Dependencies à droite, puis sur + et enfin sur JARs or directories. Accédez au répertoire extrait VODUploadDemo-java-1.4.15 et ajoutez tous les fichiers jar du répertoire lib.

    Important

    Après avoir importé les packages JAR, configurez les dépendances.

  4. Ajoutez les dépendances suivantes : Alibaba Cloud SDK for Java, OSS SDK, ApsaraVideo VOD server-side SDK et ApsaraVideo VOD upload SDK.

    Important
    • Toutes les dépendances répertoriées sont requises. L'absence de l'une d'entre elles entraîne un échec de l'intégration.

    • Si vous utilisez le dernier package JAR (aliyun-java-vod-upload-1.4.15.jar), assurez-vous que la version d'aliyun-sdk-oss est 3.9.0 ou ultérieure et que la version d'aliyun-java-sdk-vod est 2.16.11 ou ultérieure.

    • ApsaraVideo VOD est disponible dans les régions Chine (Shanghai), Chine (Shenzhen) et Chine (Pékin). Pour les téléversements vers la région Chine (Shenzhen) ou Chine (Pékin) : le SDK de téléversement 1.4.14 ou antérieur nécessite aliyun-java-sdk-vod 2.15.11+ et aliyun-java-sdk-core 4.4.5+ ; le SDK de téléversement 1.4.15 ou ultérieur nécessite aliyun-java-sdk-vod 2.16.11+ et aliyun-java-sdk-core 4.4.5+.

    Afficher les dépendances

       <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>
         <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-vod</artifactId>
            <version>2.16.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun.vod</groupId>
            <artifactId>upload</artifactId>
            <version>1.4.15</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/aliyun-java-vod-upload-1.4.15.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
                            

Scénario 1 : Téléchargement de fichiers audio et vidéo

Fichiers audio et vidéo standards

ApsaraVideo VOD propose quatre méthodes pour télécharger des fichiers audio et vidéo :

  • Téléchargement d'un fichier local. Cette méthode utilise un téléchargement multipart avec prise en charge de la reprise. Exemple : testUploadVideo.

    • Sans reprise, les tâches s'exécutent pendant un maximum de 3 000 secondes. La taille maximale du fichier dépend de la bande passante réseau et des E/S disque.

    • Si la reprise est activée, vous pouvez télécharger un fichier unique d'une taille maximale de 48,8 To.

      Important

      La reprise écrit la progression dans un fichier local, ce qui peut affecter la vitesse de téléchargement. Envisagez d'activer cette fonctionnalité pour les fichiers volumineux.

  • Téléchargement d'un flux réseau via une URL. Prend en charge la reprise pour les fichiers jusqu'à 48,8 To. Le fichier est d'abord téléchargé localement avant l'envoi ; assurez-vous de disposer d'un espace disque suffisant. Exemple : testUploadURLStream.

  • Téléchargement d'un flux de fichier à partir d'un fichier local. Aucune reprise n'est possible. Taille maximale du fichier : 5 Go. Exemple : testUploadFileStream.

  • Téléchargement d'un flux d'entrée (flux de fichier ou flux réseau). Aucune reprise n'est possible. Taille maximale du fichier : 5 Go. Exemple : testUploadStream.

Important

Lorsque vous utilisez l'exemple de code, importez manuellement les classes requises. Si vous rencontrez des erreurs de dépendance manquante, consultez la FAQ.

Exemple de code

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

Fichiers M3U8

Exemple de code

public class UploadVideoDemo {
    // Required: Specify your AccessKey pair.
    // An AccessKey pair from an Alibaba Cloud account can access all APIs. We recommend that you use a RAM user for API access or routine O&M.
    // Do not hard-code the AccessKey ID and AccessKey Secret in your project. Otherwise, the AccessKey pair may be leaked and all the resources in your account may be exposed to risks.
    // In this example, the AccessKey pair is obtained from environment variables. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    public static void main(String[] args) {
    // Upload an M3U8 file.
        // 1. Upload a local M3U8 audio or video file.
        testUploadLocalM3u8(accessKeyId, accessKeySecret);
        // 2. Upload an online M3U8 audio or video file.
        testUploadWebM3u8(accessKeyId, accessKeySecret);
    }
    /**
     * Uploads a local M3U8 audio or video file to ApsaraVideo VOD. By default, the M3U8 file and its TS files are in the same directory. If sliceFilenames is not specified, the TS file paths are parsed from the M3U8 file.
     *
     * @param request The request to upload a local M3U8 file.
     *                m3u8Filename: The absolute path of the local M3U8 index file. The TS file paths in the M3U8 file must be relative. These paths cannot contain URLs or absolute local paths.
     *                sliceFilenames: The list of the absolute paths of the TS files. If you specify this parameter, the specified paths are used. If you do not specify this parameter, the M3U8 file specified by m3u8Filename is parsed.
     */
    private static void testUploadLocalM3u8(String accessKeyId, String accessKeySecret) {
        String title = "test_upload_local_m3u8";
        String m3u8Filename = "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/cc38da35c7b24de0abe58619cdd7****-6479a12446b994719838e0307f****-ld.m3u8";
        UploadLocalM3u8Request request = new UploadLocalM3u8Request(accessKeyId, accessKeySecret, title, m3u8Filename);
        String[] sliceFilenames = new String[]{
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00001.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00002.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00003.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00004.ts",
                "/Users/test/0e9ecfc6da934d1887ed7bdfc925****/slices/cc38da35c7b24de0abe58619cdd7****-c45797a1ad6e75fbb9d1a8493703****-ld-00005.ts"
        };
        // Optional. The list of absolute paths for the TS files. If you do not specify this parameter, the TS file paths are obtained by parsing the M3U8 file.
        request.setSliceFilenames(sliceFilenames);
        /* The part size for multipart upload. Default value: 2 MB. */
        request.setPartSize(2 * 1024 * 1024L);
        /* The number of concurrent threads for multipart upload. Default value: 1. This parameter affects CPU consumption. Set this value based on your server's configuration. */
        request.setTaskNum(1);
        /* Optional. Specifies whether to add a watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
        //request.setShowWaterMark(true);
        /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable it. */
        //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
        /* Optional. The video category ID. */
        //request.setCateId(-1L);
        /* Optional. The video tags. Separate multiple tags with commas (,). */
        //request.setTags("Tag1,Tag2");
        /* Optional. The video description. */
        //request.setDescription("Video description");
        /* Optional. The thumbnail URL. */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* Optional. The template group ID. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* Optional. The workflow ID. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* Optional. The storage location. */
        //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
        /* The application ID. */
        // request.setAppId("app-1000000");
        /* The region where ApsaraVideo VOD is activated. */
        // request.setApiRegionId("cn-shanghai");
        /* The region where the ECS instance is deployed. */
        // request.setEcsRegionId("cn-shanghai");
        /* Optional. The proxy settings. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The host address of the proxy server. */
        //ossConfig.setProxyHost("");
        /* Required. The port number of the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* The protocol that is used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("");
        /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("");
        /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("");
        //request.setOssConfig(ossConfig);
        UploadM3u8FileImpl uploadM3u8File = new UploadM3u8FileImpl();
        UploadLocalM3u8Response uploadLocalM3u8Response = uploadM3u8File.uploadLocalM3u8(request);
        System.out.println("code = " + uploadLocalM3u8Response.getCode());
        System.out.println("message = " + uploadLocalM3u8Response.getMessage());
        System.out.println("videoId = " + uploadLocalM3u8Response.getVideoId());
        System.out.println("requestId = " + uploadLocalM3u8Response.getRequestId());
    }
    /**
     * Uploads an online M3U8 audio or video file to ApsaraVideo VOD. This method first downloads the file to a temporary local directory and then uploads the file to ApsaraVideo VOD storage. Make sure that the local disk has sufficient space.
     *
     * @param request The request to upload an online M3U8 file.
     *                m3u8FileURL: The URL of the online M3U8 index file. The TS file paths in the M3U8 file must be relative. These paths cannot contain URLs or absolute local paths.
     *                sliceFileURLs: The list of the URLs of the TS files. You must construct the URLs of the TS files.
     */
    private static void testUploadWebM3u8(String accessKeyId, String accessKeySecret) {
        String title = "test_upload_web_m3u8";
        String m3u8FileURL = "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-538087dcf2c201c31ce4324bf76af69****.m3u8";
        UploadWebM3u8Request request = new UploadWebM3u8Request(accessKeyId, accessKeySecret, title, m3u8FileURL);
        String[] sliceFileURLs = new String[]{
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts",
                "http://test.aliyun.com/f0d644abc547129e957b386f77****/a0e1e2817ab9425aa558fe67a90e****-822598b9c170a8c6dad985e20cd9c27d-ld-0****.ts"
        };
        // Optional. The URLs of the TS files. If you do not specify this parameter, the TS file URLs are obtained by parsing the m3u8FileURL parameter.
        request.setSliceFileURLs(sliceFileURLs);
        /* The temporary storage directory for the downloaded files. You can specify a custom directory. If you do not specify this parameter, the files are saved to the current working directory. */
        // request.setGlobalLocalFilePath("/User/download/");
        /* The part size for multipart upload. Default value: 2 MB. */
        request.setPartSize(2 * 1024 * 1024L);
        /* The number of concurrent threads for multipart upload. Default value: 1. This parameter affects CPU consumption. Set this value based on your server's configuration. */
        request.setTaskNum(1);
        /* Optional. Specifies whether to add a watermark. If you specify a template group ID, the watermark settings in the template group prevail. */
        //request.setShowWaterMark(true);
        /* Optional. The custom settings, message callback settings, and upload acceleration settings. Extend specifies the custom settings, MessageCallback specifies the message callback settings, and AccelerateConfig specifies the upload acceleration settings. You can use the upload acceleration feature only after you enable it. */
        //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
        /* Optional. The video category ID. */
        //request.setCateId(-1L);
        /* Optional. The video tags. Separate multiple tags with commas (,). */
        //request.setTags("Tag1,Tag2");
        /* Optional. The video description. */
        //request.setDescription("Video description");
        /* Optional. The thumbnail URL. */
        //request.setCoverURL("http://cover.example.com/sample.jpg");
        /* Optional. The template group ID. */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56****");
        /* Optional. The workflow ID. */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
        /* Optional. The storage location. */
        //request.setStorageLocation("in-2017032321****-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /* The application ID. */
        //request.setAppId("app-100****");
        /* The region where ApsaraVideo VOD is activated. */
        //request.setApiRegionId("cn-shanghai");
        /* The region where the ECS instance is deployed. */
        // request.setEcsRegionId("cn-shanghai");
        /* Optional. The proxy settings. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The host address of the proxy server. */
        //ossConfig.setProxyHost("");
        /* Required. The port number of the proxy server. */
        //ossConfig.setProxyPort(-1);
        /* The protocol that is used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The user agent, which is the User-Agent header in HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("");
        /* The username that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("");
        /* The password that is used for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("");
        //request.setOssConfig(ossConfig);
        UploadM3u8FileImpl uploadM3u8File = new UploadM3u8FileImpl();
        UploadWebM3u8Response uploadWebM3u8Response = uploadM3u8File.uploadWebM3u8(request);
        System.out.println("code = " + uploadWebM3u8Response.getCode());
        System.out.println("message = " + uploadWebM3u8Response.getMessage());
        System.out.println("videoId = " + uploadWebM3u8Response.getVideoId());
        System.out.println("requestId = " + uploadWebM3u8Response.getRequestId());
    }
}

Accélération des téléchargements

Pour les fichiers volumineux (de l’ordre du Go ou du To) ou les téléchargements interrégionaux (par exemple, depuis la Chine continentale vers la région de stockage Singapour), activez l’accélération des téléchargements. Activer l’accélération des téléchargements. Une fois cette fonctionnalité activée, ajoutez la paire clé-valeur key-value AccelerateConfig à l’objet UserData dans la configuration de téléchargement. Créez l’objet UserData s’il n’existe pas déjà. Voici un exemple :

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

Paramètres

Parameter

Type

Description

Type

String

Le service pour lequel vous souhaitez activez l'accélération du téléchargement. Définissez cette valeur sur oss.

Domain

String

L'endpoint accéléré de votre bucket. Le protocole par défaut est HTTPS.

Remarque

Utilisez l'endpoint accéléré fourni après avoir activé cette fonctionnalité, par exemple vod-***.oss-accelerate.aliyuncs.com.

Scénario 2 : Télécharger des images

Afficher l'exemple de code

public class UploadImageDemo {
    // Required. The AccessKey pair of your Alibaba Cloud account.
    // An Alibaba Cloud account's AccessKey pair can access all APIs. We recommend that you use a RAM user for API access or routine operations.
    // We strongly recommend that you do not hard-code your AccessKey ID and AccessKey secret in your project code. This can leak your credentials and compromise the security of all resources in your account.
    // This example obtains an AccessKey pair from environment variables. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    public static void main(String[] args) {
        // Upload an image.
        // 1. Upload an image from a local file.
         testUploadImageLocalFile(accessKeyId, accessKeySecret);
        // 2. Upload an image by using a file or network stream.
         testUploadImageStream(accessKeyId, accessKeySecret);
    }
    /**
     * Uploads an image from a local file.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageLocalFile(String accessKeyId, String accessKeySecret) {
        /* Required. The type of the image. Valid values: default, cover, and watermark. */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        request.setImageType("cover");
        /* Optional. The image file extension. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* Optional. The image title. The title must be in UTF-8 and cannot exceed 128 bytes. */
        //request.setTitle("Image title");
        /* Optional. The image tags. You can add up to 16 tags, separated by commas (,). Each tag must be in UTF-8 and cannot exceed 32 bytes. */
        //request.setTags("Tag1,Tag2");
        /* Optional. The storage location. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* For streaming upload, the InputStream parameter is required. The fileName parameter (the name of the source file) is optional. Example: filename.png. */
        String fileName = "/Users/demo/png/test.png";
        request.setFileName(fileName);
        /* Enables the default upload progress callback. */
        //request.setPrintProgress(false);
        /* Sets a custom upload progress callback. You must inherit from VoDProgressListener. */
        /* This feature is disabled by default. If enabled, the server logs upload details during the upload process. Disable this feature if you do not need these logs. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Optional. The application ID. */
        //request.setAppId("app-100****");
        /* The region ID for the ApsaraVideo VOD access point. */
        //request.setApiRegionId("cn-shanghai");
        /* Optional. Configures a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server's host address. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server's port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        UploadImageImpl uploadImage = new UploadImageImpl();
        UploadImageResponse response = uploadImage.upload(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");
        if (response.isSuccess()) {
            System.out.print("ImageId=" + response.getImageId() + "\n");
            System.out.print("ImageURL=" + response.getImageURL() + "\n");
        } else {
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
    }
    /**
     * Uploads an image from a stream. This method supports both file and network streams.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadImageStream(String accessKeyId, String accessKeySecret) {
        /* Required. The type of the image. Valid values: default, cover, and watermark. */
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        /* Optional. The image file extension. Valid values: png, jpg, and jpeg. */
        //request.setImageExt("png");
        /* Optional. The image title. The title must be in UTF-8 and cannot exceed 128 bytes. */
        //request.setTitle("Image title");
        /* Optional. The image tags. You can add up to 16 tags, separated by commas (,). Each tag must be in UTF-8 and cannot exceed 32 bytes. */
        //request.setTags("Tag1,Tag2");
        /* Optional. The storage location. */
        //request.setStorageLocation("out-4f3952f78c0211e8b30200****.oss-cn-shanghai.aliyuncs.com");
        /* For streaming upload, the InputStream parameter is required. The fileName parameter (the name of the source file) is optional. Example: filename.png. */
        //request.setFileName("Test file name.png");
        /* Enables the default upload progress callback. */
        // request.setPrintProgress(true);
        /* Sets a custom upload progress callback. You must inherit from VoDProgressListener. */
        /* This feature is disabled by default. If enabled, the server logs upload details during the upload process. Disable this feature if you do not need these logs. */
        // request.setProgressListener(new PutObjectProgressListener());
        /* Optional. The application ID. */
        //request.setAppId("app-1000000");
        /* Optional. Configures a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* <Required> The proxy server's host address. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* <Required> The proxy server's port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        // 1. Upload a file stream.
        // InputStream fileStream = getFileStream(request.getFileName());
        // if (fileStream != null) { 
        //     request.setInputStream(fileStream);
        // }
        // 2. Upload a network stream.
        String url = "http://test.aliyun.com/image/default/test.png";
        InputStream urlStream = getUrlStream(url);
        if (urlStream != null) {
            request.setInputStream(urlStream); 
       }
        // Start the image upload.
        UploadImageImpl uploadImage = new UploadImageImpl();
        UploadImageResponse response = uploadImage.upload(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");
        if (response.isSuccess()) {
            System.out.print("ImageId=" + response.getImageId() + "\n");
            System.out.print("ImageURL=" + response.getImageURL() + "\n");
        } else {
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
    }
    private static InputStream getFileStream(String fileName) {
        try {
            return new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    private static InputStream getUrlStream(String url) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}          
Remarque

Par défaut, la validité du paramètre ImageURL est de 3 600 secondes (1 heure). Cette durée est fixe et ne peut pas être personnalisée via les paramètres de l'API ou les configurations du SDK. L'expiration repose sur le mécanisme d'URL signée d'OSS et est calculée indépendamment de l'expiration de la signature d'URL CDN, que vous pouvez configurer dans la console CDN. Il est donc normal que ces deux durées d'expiration diffèrent.

Scénario 3 : Télécharger des ressources multimédias auxiliaires

Exemple de code

public class UploadAttachedMediaDemo {
    // Required. The AccessKey pair of your account.
    // An AccessKey pair for an Alibaba Cloud account grants full access to all API operations. We recommend using a RAM user for API access and routine O&M.
    // To prevent leaks, do not hard-code your AccessKey ID and AccessKey Secret in your project. A leaked AccessKey pair can compromise the security of all resources in your account.
    // This example retrieves an AccessKey pair from environment variables for identity verification. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    public static void main(String[] args) {
        // Upload auxiliary media assets.
        // Upload an auxiliary media asset from a local file.
        testUploadAttachedMediaLocalFile(accessKeyId, accessKeySecret);
        // Upload an auxiliary media asset by using streaming upload (file stream and network stream).
        testUploadAttachedMediaStream(accessKeyId, accessKeySecret);
    }
 /**
     * Uploads a local auxiliary media asset.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaLocalFile(String accessKeyId, String accessKeySecret) {
        /* The business type. */
        String businessType = "watermark";
        /* The file name extension. */
        String mediaExt = "png";
        String filename = "/Users/demo/png/test.png";
        UploadAttachedMediaRequest request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
        request.setFileName(filename);
        /* The title. */
        request.setTitle("test_attached_media");
        /* The category ID. */
        request.setCateId(-1L);
        /* Optional. The tags. Separate multiple tags with commas. */
        request.setTags("tag1,tag2");
        /* Optional. The description. */
        request.setDescription("test_desc");
        /* Optional. The storage location. */
        request.setStorageLocation("out-20170323225118266-5l3hs5****.oss-cn-shanghai.aliyuncs.com");
        /* The access region of ApsaraVideo VOD. */
        request.setApiRegionId("cn-shanghai");
        /* The application ID. */
        //request.setAppId("app-1000000");
        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The proxy host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. The proxy port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();
        UploadAttachedMediaResponse response = uploader.upload(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");
        if (response.isSuccess()) {
            System.out.print("MediaId=" + response.getMediaId() + "\n");
            System.out.print("MediaURL=" + response.getMediaURL() + "\n");
            System.out.print("FileURL=" + response.getFileURL() + "\n");
        } else {
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
    }
     /**
     * Uploads an auxiliary media asset by using streaming upload. This method supports file streams and network streams.
     *
     * @param accessKeyId
     * @param accessKeySecret
     */
    private static void testUploadAttachedMediaStream(String accessKeyId, String accessKeySecret) {
        /* The business type. */
        String businessType = "watermark";
        /* The file name extension. */
        String mediaExt = "png";
        String filename = "http://test.aliyun.com/test.png";
        UploadAttachedMediaRequest request;
        // 1. Upload from a file stream.
        InputStream fileStream = getFileStream(filename);
        request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
        request.setInputStream(fileStream);
        // 2. Upload from a network stream.
//        String url = "http://test.aliyun.com/image//test.png";
//        InputStream urlStream = getUrlStream(url);
//        request = new UploadAttachedMediaRequest(accessKeyId, accessKeySecret, businessType, mediaExt);
//        request.setInputStream(urlStream);
        /* The title. */
        request.setTitle("test_attached_media");
        /* The category ID. */
        request.setCateId(-1L);
        /* Optional. The tags. Separate multiple tags with commas. */
        request.setTags("tag1,tag2");
        /* Optional. The description. */
        request.setDescription("test_desc");
        /* Optional. The storage location. */
        request.setStorageLocation("out-20170323225118266-5l3****wa.oss-cn-shanghai.aliyuncs.com");
        /* The access region of ApsaraVideo VOD. */
        request.setApiRegionId("cn-shanghai");
        /* The application ID. */
        // request.setAppId("app-1000000");
        /* Optional. Configure a proxy. */
        //OSSConfig ossConfig = new OSSConfig();
        /* Required. The proxy host. */
        //ossConfig.setProxyHost("<yourProxyHost>");
        /* Required. The proxy port. */
        //ossConfig.setProxyPort(-1);
        /* The protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. */
        //ossConfig.setProtocol("HTTP");
        /* The User-Agent header for HTTP requests. Default value: aliyun-sdk-java. */
        //ossConfig.setUserAgent("<yourUserAgent>");
        /* The username for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyUsername("<yourProxyUserName>");
        /* The password for proxy server authentication. This parameter is required if you use the HTTPS protocol. */
        //ossConfig.setProxyPassword("<yourProxyPassword>");
        //request.setOssConfig(ossConfig);
        // Start the upload.
        UploadAttachedMediaImpl uploader = new UploadAttachedMediaImpl();
        UploadAttachedMediaResponse response = uploader.upload(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");
        if (response.isSuccess()) {
            System.out.print("MediaId=" + response.getMediaId() + "\n");
            System.out.print("MediaURL=" + response.getMediaURL() + "\n");
            System.out.print("FileURL=" + response.getFileURL() + "\n");
        } else {
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
    }
    private static InputStream getFileStream(String fileName) {
        try {
            return new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    private static InputStream getUrlStream(String url) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Fonctionnalités avancées

  • Barre de progression du chargement

    Le fichier PutObjectProgressListener.java situé dans le répertoire sample fournit une implémentation de rappel pour le suivi de la progression du chargement.

    Cette classe implémente l'interface VoDProgressListener . Un objet ProgressEvent signale la progression du chargement du fichier vers OSS, ce qui vous permet d'ajouter une logique personnalisée pour chaque événement.

    L'exemple de code ci-dessous illustre cette fonctionnalité.

    Afficher l'exemple de code

    /**
     * An implementation of a listener for upload progress callbacks.
     * This callback is invoked only if you enable upload progress notifications.
     * A callback event is triggered when a multipart upload to OSS succeeds or fails. You can implement custom logic to handle the event.
     * When uploading an audio or video file, this callback provides the `videoId`, which you can use to manage the file.
     * When uploading an image, this callback provides the `imageId`, which you can use to manage the image.
     */
    public class PutObjectProgressListener implements VoDProgressListener {
        /**
         * Number of bytes that have been successfully uploaded to OSS.
         */
        private long bytesWritten = 0;
        /**
         * Total size of the source file in bytes.
         */
        private long totalBytes = -1;
        /**
         * Indicates whether the upload completed successfully.
         */
        private boolean succeed = false;
        /**
         * The video ID.
         */
        private String videoId;
        /**
         * The image ID.
         */
        private String imageId;
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
                // Indicates that the upload started.
                case TRANSFER_STARTED_EVENT:
                    if (videoId != null) {
                        System.out.println("Start to upload videoId "+videoId+"......");
                    }
                    if (imageId != null) {
                        System.out.println("Start to upload imageId "+imageId+"......");
                    }
                    break;
                // Provides the total size of the file to be uploaded. This event is supported only for local file uploads.
                case REQUEST_CONTENT_LENGTH_EVENT:
                    this.totalBytes = bytes;
                    System.out.println(this.totalBytes + "bytes in total will be uploaded to OSS.");
                    break;
                // Indicates the number of bytes that have been transferred.
                case REQUEST_BYTE_TRANSFER_EVENT:
                    this.bytesWritten += bytes;
                    if (this.totalBytes != -1) {
                        int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                        System.out.println(bytes+" bytes have been written at this time, upload progress: "+
                                percent +"%(" +  this.bytesWritten +  "/"  + this.totalBytes  + ")");
                    } else {
                        System.out.println(bytes + " bytes have been written at this time, upload sub total : " +
                                "(" + this.bytesWritten + ")");
                    }
                    break;
                // Indicates that the transfer is complete.
                case TRANSFER_COMPLETED_EVENT:
                    this.succeed = true;
                    if (videoId != null) {
                        System.out.println("Succeed to upload videoId "  + videoId  + " , " + this.bytesWritten + " bytes have been transferred in total.");
                    }
                    if (imageId != null) {
                        System.out.println("Succeed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred in total.");
                    }
                    break;
                // Indicates that the transfer failed.
                case TRANSFER_FAILED_EVENT:
                    if (videoId != null) {
                        System.out.println("Failed to upload videoId " + videoId + " , " + this.bytesWritten + " bytes have been transferred.");
                    }
                    if (imageId != null) {
                        System.out.println("Failed to upload imageId " + imageId + " , " + this.bytesWritten + " bytes have been transferred.");
                    }
                    break;
                default:
                    break;
            }
        }
        public boolean isSucceed() {
            return succeed;
        }
        public void onVidReady(String videoId) {
            setVideoId(videoId);
        }
        public void onImageIdReady(String imageId) {
            setImageId(imageId);
        }
        public String getVideoId() {
            return videoId;
        }
        public void setVideoId(String videoId) {
            this.videoId = videoId;
        }
        public String getImageId() {
            return imageId;
        }
        public void setImageId(String imageId) {
            this.imageId = imageId;
        }
    }
                        
  • Actualisation d'un jeton temporaire

    Le fichier RefreshSTSTokenImpl.java situé dans le répertoire sample montre comment actualiser un jeton temporaire.

    L'exemple de code ci-dessous illustre cette procédure.

    Afficher l'exemple de code

    /**
     * @author vod
     * An implementation that retrieves a temporary token from Security Token Service (STS).
     * @date 2019/6/5
     */
    public class RefreshSTSTokenImpl implements VoDRefreshSTSTokenListener {
        public STSTokenDTO onRefreshSTSToken() {
            STSTokenDTO stsTokenDTO = new STSTokenDTO();
            stsTokenDTO.setAccessKeyId("<Your STS AccessKeyId>");
            stsTokenDTO.setAccessKeySecret("<Your STS AccessKeySecret>");
            stsTokenDTO.setSecurityToken("<Your STS SecurityToken>");
            return stsTokenDTO;
        }
    }

FAQ

Problème 1 : Erreurs de dépendance manquante

  1. Dans votre projet Maven, cliquez sur Maven à droite, puis sur l'icône m, et saisissez mvn idea:module pour recharger les ressources.

  2. Dans la barre de menus supérieure, sélectionnez Build > Rebuild Project.

  3. Copiez le fichier aliyun-java-vod-upload-1.4.15.jar dans le répertoire des ressources de votre projet et ajoutez une dépendance Maven locale :

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

    Exemple de dépendances Maven après l'ajout de la dépendance locale.

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

Problème 2 : Erreur NoClassDefFoundError lors du chargement de fichiers M3U8

Lors du chargement d'un fichier M3U8, l'erreur suivante se produit :

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

Ce problème survient car le SDK de chargement pour Java dépend en interne de la bibliothèque commons-lang3 , qui n'est pas incluse dans la liste des dépendances. Pour résoudre ce problème, ajoutez la dépendance suivante à votre fichier pom.xml et reconstruisez votre projet :

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