Tüm Ürünler
Search
Belge Merkezi

ApsaraVideo VOD:Upload files with the Java SDK

Son Güncelleme:Oct 05, 2026

ApsaraVideo VOD hizmetine ses, video, görüntü ve yardımcı medya dosyalarını yüklemek için Java sunucu tarafı yükleme SDK'sını kullanın.

Genel bakış

Java yükleme SDK'sı, ApsaraVideo VOD yükleme sürecini takip eder. Temel adımlar şunlardır:

  1. Ön koşulları tamamlayın.

  2. Java yükleme SDK'sını entegre edin.

  3. Yükleme mantığını (öncelikli olarak yükleme yapılandırmasını) uygulayın.

Ön koşullar

  • ApsaraVideo VOD'u etkinleştirin. Daha fazla bilgi için bkz. ApsaraVideo VOD'u etkinleştirme.

  • Belirtilen bölgedeki depolama yolu ve geri arama ayarları dahil olmak üzere yükleme için gereken sistem ayarlarını yapılandırın. Daha fazla bilgi için bkz. Depolama paketlerini yönetme ve Geri aramaları yapılandırma.

  • Bir RAM kullanıcısı oluşturun ve ApsaraVideo VOD'a erişmek için bu kullanıcıyı kullanın. Alibaba Cloud hesabınızın AccessKey çiftinin sızması nedeniyle oluşabilecek güvenlik risklerini önlemek için bir RAM kullanıcısı oluşturmanızı ve bu kullanıcıya ApsaraVideo VOD'a erişim için gerekli izinleri vermenizi öneririz. Ardından, RAM kullanıcısının AccessKey çifti ile ApsaraVideo VOD'a erişebilirsiniz. Daha fazla bilgi için bkz. RAM kullanıcısı oluşturma ve izin verme.

  • ALIBABA_CLOUD_ACCESS_KEY_ID ve ALIBABA_CLOUD_ACCESS_KEY_SECRET ortam değişkenlerini yapılandırın. Daha fazla bilgi için bkz. Linux, macOS ve Windows'ta ortam değişkenlerini yapılandırma.

    Önemli
    • Bir Alibaba Cloud hesabının AccessKey çifti tüm API işlemleri üzerinde izne sahiptir. API işlemlerini çağırmak veya rutin bakım ve işletim işlemleri yapmak için bir RAM kullanıcısının AccessKey çiftini kullanın.

    • AccessKey ID ve AccessKey Secret değerlerini proje koduna sabit kod olarak eklemeyin. Bu bilgiler sızdığı takdirde hesabınızdaki tüm kaynaklar tehlikeye girer.

  • İsteğe bağlı. Security Token Service (STS) kullanarak ApsaraVideo VOD'a erişmek istiyorsanız, RAM kullanıcısı için bir rol oluşturun ve bu role ApsaraVideo VOD'a erişim için gerekli izinleri atayın. Daha fazla bilgi için bkz. STS belirteci alma.

Java için yükleme SDK'sını entegre etme

Not

Bu örnekte Java 1.8+ ve Java için yükleme SDK'sı 1.4.15 sürümü kullanılmıştır. Adımlar sürüme göre değişiklik gösterebilir. SDK, manuel JAR içe aktarmayı gerektirir; doğrudan bağımlılık entegrasyonu desteklenmez. Sorun giderme.

  1. Java için yükleme SDK'sını ve örnek kodu indirin.

  2. İndirilen paketi açın.

    VODUploadDemo-java-1.4.15.zip dosyasını çıkardıktan sonra aşağıdaki klasörleri elde edersiniz:

    • lib: Yükleme SDK'sı için gerekli JAR paketleri.

    • sample: Yükleme SDK'sı için örnek kod.

  3. JAR paketlerini içe aktarın.

    • Eclipse: Projenize sağ tıklayın, Properties > Java Build Path > Add JARs öğelerini seçin, çıkarılan VODUploadDemo-java-1.4.15 klasörüne gidin ve lib dizinindeki tüm jar dosyalarını ekleyin.

    • IntelliJ IDEA: File > Project Structure > Modules öğelerini seçin, sağ taraftaki Dependencies sekmesine tıklayın, + işaretine ve ardından JARs or directories seçeneğine tıklayın. Çıkarılan VODUploadDemo-java-1.4.15 dizinine gidin ve lib dizinindeki tüm jar dosyalarını ekleyin.

    Önemli

    JAR paketlerini içe aktardıktan sonra bağımlılıkları yapılandırın.

  4. Bağımlılıkları ekleyin: Alibaba Cloud SDK for Java, OSS SDK, ApsaraVideo VOD sunucu tarafı SDK'sı ve ApsaraVideo VOD yükleme SDK'sı.

    Önemli
    • Listelenen tüm bağımlılıklar gereklidir. Herhangi birinin eksik olması entegrasyonun başarısız olmasına neden olur.

    • En son JAR paketini (aliyun-java-vod-upload-1.4.15.jar) kullanıyorsanız, aliyun-sdk-oss sürümünün 3.9.0 veya üzeri, aliyun-java-sdk-vod sürümünün ise 2.16.11 veya üzeri olduğundan emin olun.

    • ApsaraVideo VOD, Çin (Şanghay), Çin (Shenzhen) ve Çin (Pekin) bölgelerinde kullanılabilir. Çin (Shenzhen) veya Çin (Pekin) bölgelerine yükleme yaparken: Yükleme SDK'sı 1.4.14 veya önceki sürümler için aliyun-java-sdk-vod 2.15.11+ ve aliyun-java-sdk-core 4.4.5+ gerekir; yükleme SDK'sı 1.4.15 veya sonraki sürümler için aliyun-java-sdk-vod 2.16.11+ ve aliyun-java-sdk-core 4.4.5+ gerekir.

    Bağımlılıkları göster

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

Senaryo 1: Ses ve video dosyalarını yükleme

Normal ses ve video dosyaları

ApsaraVideo VOD, ses ve video dosyalarını yüklemek için dört yöntem sunar:

  • Yerel bir dosya yükleyin. Yeniden başlatılabilir yükleme desteğiyle çok parçalı yükleme kullanır. Örnek: testUploadVideo.

    • Yeniden başlatılabilir yükleme olmadan görevler en fazla 3.000 saniye çalışır. Maksimum dosya boyutu ağ bant genişliğine ve disk G/Ç hızına bağlıdır.

    • Yeniden başlatılabilir yükleme etkinleştirilirse, tek bir dosyanın boyutu 48,8 TB'a kadar olabilir.

      Önemli

      Yeniden başlatılabilir yükleme, ilerleme durumunu yerel bir dosyaya yazar; bu durum yükleme hızını etkileyebilir. Büyük dosyalar için bu özelliği etkinleştirmeyi düşünün.

  • URL üzerinden bir ağ akışı yükleyin. 48,8 TB'a kadar olan dosyalar için yeniden başlatılabilir yüklemeyi destekler. Dosyayı yüklemeden önce yerel olarak indirir; yeterli disk alanı olduğundan emin olun. Örnek: testUploadURLStream.

  • Yerel bir dosyadan bir dosya akışı yükleyin. Yeniden başlatılabilir yükleme yoktur. Maksimum dosya boyutu: 5 GB. Örnek: testUploadFileStream.

  • Bir giriş akışı (dosya akışı veya ağ akışı) yükleyin. Yeniden başlatılabilir yükleme yoktur. Maksimum dosya boyutu: 5 GB. Örnek: testUploadStream.

Önemli

Örnek kodu kullanırken gerekli sınıfları manuel olarak içe aktarın. Eksik bağımlılık hatalarıyla karşılaşırsanız SSS bölümünü kontrol edin.

Örnek kod

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

M3U8 dosyaları

Örnek kod

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

Yükleme hızlandırma

Büyük dosyalar (GB veya TB düzeyinde) veya bölgeler arası yüklemeler (örneğin, Çin anakarasından Singapur depolama bölgesine) için yükleme hızlandırmayı etkinleştirin. Yükleme hızlandırmayı etkinleştirme. Özelliği etkinleştirdikten sonra, yükleme yapılandırmasındaki UserData nesnesine AccelerateConfig anahtar-değer çiftini ekleyin. UserData nesnesi yoksa oluşturun. Örnek:

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

Parametreler

Parametre

Tür

Açıklama

Type

String

Yükleme hızlandırmanın etkinleştirileceği hizmet. Bu değeri oss olarak ayarlayın.

Domain

String

Paketinizin hızlandırılmış uç noktası. Varsayılan protokol HTTPS'dir.

Not

Bu özelliği etkinleştirdikten sonra sağlanan hızlandırılmış uç noktayı kullanın, örneğin vod-***.oss-accelerate.aliyuncs.com.

Senaryo 2: Görüntüleri yükleme

Örnek kodu göster

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;
    }
}          
Not

Varsayılan olarak ImageURL 3.600 saniye (1 saat) süreyle geçerlidir. Bu geçerlilik süresi sistem tarafından sabitlenmiştir ve API parametreleri veya SDK ayarları kullanılarak özelleştirilemez. Süre sonu, OSS imzalı URL mekanizmasına dayanır ve CDN konsolunda yapılandırabileceğiniz CDN URL imzalama süresinden bağımsız olarak hesaplanır. Bu nedenle, iki süre sonunun farklı olması beklenen bir durumdur.

Senaryo 3: Yardımcı medya varlıklarını yükleme

Örnek kod

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

Gelişmiş özellikler

  • Yükleme ilerleme çubuğu

    sample dizinindeki PutObjectProgressListener.java dosyası, yükleme ilerlemesi için bir geri arama uygulaması sağlar.

    Bu sınıf, VoDProgressListener arabirimini uygular. Bir ProgressEvent nesnesi, dosya yükleme ilerlemesini OSS'e bildirir ve her olay için özel mantık ekleyebilirsiniz.

    Aşağıdaki kod bir örnek sunar.

    Örnek kodu göster

    /**
     * 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;
        }
    }
                        
  • Geçici belirteci yenileme

    sample dizinindeki RefreshSTSTokenImpl.java dosyası, geçici bir belirtecin nasıl yenileneceğini gösterir.

    Aşağıdaki kod bir örnek sunar.

    Örnek kodu göster

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

SSS

Sorun 1: Eksik bağımlılık hataları

  1. Maven projenizde sağ taraftaki Maven sekmesine tıklayın, m simgesine tıklayın ve kaynakları yeniden yüklemek için mvn idea:module komutunu girin.

  2. Üst menü çubuğundan Build > Rebuild Project seçeneklerini belirleyin.

  3. aliyun-java-vod-upload-1.4.15.jar dosyasını projenizin kaynaklar dizinine kopyalayın ve yerel bir Maven bağımlılığı ekleyin:

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

    Yerel bağımlılık eklendikten sonra örnek Maven bağımlılıkları.

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

**Sorun 2: M3U8 dosyalarını yüklerken NoClassDefFoundError hatası**

Bir M3U8 dosyası yüklerken aşağıdaki hata oluşur:

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

Bu sorun, Java için yükleme SDK'sının dahili olarak commons-lang3 kitaplığına bağımlı olmasından, ancak bu kitaplığın bağımlılık listesine dahil edilmemesinden kaynaklanır. Sorunu çözmek için aşağıdaki bağımlılığı pom.xml dosyanıza ekleyin ve projenizi yeniden derleyin:

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