You need to enable JavaScript to run this app.
导航
媒资上传
最近更新时间:2024.10.08 19:48:10首次发布时间:2021.02.23 10:42:40

本文为您提供了服务端 Java SDK 媒资上传模块的接口调用示例。

使用说明

  • 开始前,请阅读媒资上传概述了解媒资类型和支持格式。
  • 异步上传成功是指提交任务成功,并不代表媒资上传任务执行成功。

前提条件

调用接口前,请先完成 SDK 的安装初始化

调用示例

签发临时上传 Token

可在应用服务端通过 AK 和 SK 在本地签出临时上传 Token,不依赖外网。如希望同时生成多个临时上传 Token,您可以循环调用生成方法。临时上传 Token 用于客户端上传,详见客户端上传

package com.volcengine.example.vod.upload;

import com.alibaba.fastjson.JSON;
import com.volcengine.model.sts2.SecurityToken2;
import com.volcengine.service.vod.IVodService;
import com.volcengine.service.vod.impl.VodServiceImpl;
import com.volcengine.util.Time;


public class GetUploadSts2Demo {

    public static void main(String[] args) throws Exception {
        // Create a VOD instance in the specified region.
        // IVodService vodService = VodServiceImpl.getInstance("cn-north-1");
        IVodService vodService = VodServiceImpl.getInstance();

        // Configure your Access Key ID (AK) and Secret Access Key (SK) in the environment variables or in the local ~/.volc/config file. For detailed instructions, see https://www.volcengine.com/docs/4/65641.
        // The SDK will automatically fetch the AK and SK from the environment variables or the ~/.volc/config file as needed.
        // During testing, you may use the following code snippet. However, do not store the AK and SK directly in your project code to prevent potential leakage and safeguard the security of all resources associated with your account.
        // vodService.setAccessKey("your ak");
        // vodService.setSecretKey("your sk");

        //set expire time
        SecurityToken2 sts2WithExpire = vodService.getUploadSts2WithExpire(Time.Hour);
        System.out.println(JSON.toJSONString(sts2WithExpire));


        //expire after one hour by default
        SecurityToken2 sts2 = vodService.getUploadSts2();
        System.out.println(JSON.toJSONString(sts2));

    }
}

媒资上传

视频点播目前支持以下两个版本的获取上传地址和凭证和确认上传接口:

接口请求参数和返回参数说明详见 ApplyUploadInfoCommitUploadInfo

注意

版本号为 2022-01-01 时,上传文件必须携带文件后缀。例如,如需上传 MP4 文件,携带 .mp4.MP4

package com.volcengine.example.vod.upload;

import com.alibaba.fastjson.JSON;
import com.volcengine.helper.VodUploadMediaProcessListener;
import com.volcengine.helper.VodUploadProgressListener;
import com.volcengine.model.beans.Functions;
import com.volcengine.model.beans.FunctionsWorkflowTemplate;
import com.volcengine.service.vod.IVodService;
import com.volcengine.service.vod.impl.VodServiceImpl;
import com.volcengine.service.vod.model.business.VodUploadTemplate;
import com.volcengine.service.vod.model.request.VodUploadMediaRequest;
import com.volcengine.service.vod.model.response.VodCommitUploadInfoResponse;

import java.util.ArrayList;
import java.util.List;

public class VodUploadMediaDemo {

    public static void main(String[] args) {
        // Create a VOD instance in the specified region.
        // IVodService vodService = VodServiceImpl.getInstance("cn-north-1");
        IVodService vodService = VodServiceImpl.getInstance();

        // Configure your Access Key ID (AK) and Secret Access Key (SK) in the environment variables or in the local ~/.volc/config file. For detailed instructions, see https://www.volcengine.com/docs/4/65641.
        // The SDK will automatically fetch the AK and SK from the environment variables or the ~/.volc/config file as needed.
        // During testing, you may use the following code snippet. However, do not store the AK and SK directly in your project code to prevent potential leakage and safeguard the security of all resources associated with your account.
        // vodService.setAccessKey("your ak");
        // vodService.setSecretKey("your sk");

        String space = "your space name";
        String filePath = "your file path";

        List<Functions> functionsList = new ArrayList<>();
        Functions getMetaFunc = Functions.GetMetaFunction();
        functionsList.add(getMetaFunc);

        Functions snapShotFunc = Functions.SnapShotFunction(2.3);
        functionsList.add(snapShotFunc);

        Functions addOptionInfo = Functions.AddOptionInfoFunction("hls测试视频", "test", "素材测试,视频文件", 0, true);
        functionsList.add(addOptionInfo);


        List<String> impTemplateIds = new ArrayList<>();
        impTemplateIds.add("imp template id");
        FunctionsWorkflowTemplate impTemplate = new FunctionsWorkflowTemplate(impTemplateIds, "imp");

        List<String> transcodeTemplateIds = new ArrayList<>();
        transcodeTemplateIds.add("transcode template id");
        FunctionsWorkflowTemplate transcodeTemplate = new FunctionsWorkflowTemplate(transcodeTemplateIds,
                "transcode");

        List<FunctionsWorkflowTemplate> templates = new ArrayList<>();
        templates.add(impTemplate);
        templates.add(transcodeTemplate);
        Functions workflowFunc = Functions.StartWorkFlowFunction(templates);
        functionsList.add(workflowFunc);

        VodUploadMediaRequest vodUploadMediaRequest = VodUploadMediaRequest.newBuilder()
                .setSpaceName(space)
                .setFilePath(filePath)
                .setFileName("hello/vod/video.mp4")
                .setFunctions(JSON.toJSONString(functionsList))
                .setStorageClass(1)
                .build();
        // 需要进度条功能时添加相应 listener,如无需求,传 null 值即可
        VodUploadProgressListener listener = new VodUploadMediaProcessListener();

        try {
            VodCommitUploadInfoResponse vodCommitUploadInfoResponse = vodService.uploadMedia(vodUploadMediaRequest, listener);
            if (vodCommitUploadInfoResponse.getResponseMetadata().hasError()) {
                System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getError());
                System.exit(-1);
            }
            System.out.println(vodCommitUploadInfoResponse.toString());
            System.out.println(vodCommitUploadInfoResponse.getResult().getData().getVid());
            System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getRequestId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

素材上传

视频点播目前支持以下两个版本的获取上传地址和凭证和确认上传接口:

接口请求参数和返回参数说明详见 ApplyUploadInfoCommitUploadInfo

注意

版本号为 2022-01-01 时,上传文件必须携带文件后缀。例如,如需上传 MP4 文件,携带 .mp4.MP4

package com.volcengine.example.vod.upload;

import com.alibaba.fastjson.JSON;
import com.volcengine.service.vod.Const;
import com.volcengine.model.beans.Functions;
import com.volcengine.service.vod.IVodService;
import com.volcengine.service.vod.impl.VodServiceImpl;
import com.volcengine.service.vod.model.request.VodUploadMaterialRequest;
import com.volcengine.service.vod.model.response.VodCommitUploadInfoResponse;

import java.util.ArrayList;
import java.util.List;

public class VodUploadMaterialDemo {

    public static void main(String[] args) {
        // Create a VOD instance in the specified region.
        // IVodService vodService = VodServiceImpl.getInstance("cn-north-1");
        IVodService vodService = VodServiceImpl.getInstance();

        // Configure your Access Key ID (AK) and Secret Access Key (SK) in the environment variables or in the local ~/.volc/config file. For detailed instructions, see https://www.volcengine.com/docs/4/65641.
        // The SDK will automatically fetch the AK and SK from the environment variables or the ~/.volc/config file as needed.
        // During testing, you may use the following code snippet. However, do not store the AK and SK directly in your project code to prevent potential leakage and safeguard the security of all resources associated with your account.
        // vodService.setAccessKey("your ak");
        // vodService.setSecretKey("your sk");

        String space = "your space name";
        String filePath = "your file path";

        List<Functions> functionsList = new ArrayList<>();
        Functions getMetaFunc = Functions.GetMetaFunction();
        functionsList.add(getMetaFunc);

        Functions snapShotFunc = Functions.SnapShotFunction(2.3);
        functionsList.add(snapShotFunc);

        Functions addOptionInfo = Functions.AddOptionInfoFunction("素材测试视频", "test", "素材测试,视频文件", Const.CategoryVideo, "mp4");
        functionsList.add(addOptionInfo);

        VodUploadMaterialRequest vodUploadMaterialRequest = VodUploadMaterialRequest.newBuilder()
                .setSpaceName(space)
                .setFilePath(filePath)
                .setFileType(Const.FileTypeMedia)
                .setFunctions(JSON.toJSONString(functionsList))
                .build();

        try {
            VodCommitUploadInfoResponse vodCommitUploadInfoResponse = vodService.uploadMaterial(vodUploadMaterialRequest, null);
            if (vodCommitUploadInfoResponse.getResponseMetadata().hasError()) {
                System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getError());
                System.exit(-1);
            }
            System.out.println(vodCommitUploadInfoResponse.toString());
            System.out.println(vodCommitUploadInfoResponse.getResult().getData().getMid());
            System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getRequestId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

////  图片素材上传
//    public static void main(String[] args) {
//        IVodService vodService = VodServiceImpl.getInstance();
//
//        // Configure your Access Key ID (AK) and Secret Access Key (SK) in the environment variables or in the local ~/.volc/config file. For detailed instructions, see https://www.volcengine.com/docs/4/65641.
//        // The SDK will automatically fetch the AK and SK from the environment variables or the ~/.volc/config file as needed.
//        // During testing, you may use the following code snippet. However, do not store the AK and SK directly in your project code to prevent potential leakage and safeguard the security of all resources associated with your account.
//        vodService.setAccessKey("your ak");
//        vodService.setSecretKey("your sk");
//
//        String space = "your space name";
//        String filePath = "your file path";
//
//        List<Functions> functionsList = new ArrayList<>();
//        Functions getMetaFunc = Functions.GetMetaFunction();
//        functionsList.add(getMetaFunc);
//
//        Functions snapShotFunc = Functions.SnapShotFunction(2.3);
//        functionsList.add(snapShotFunc);
//
//        Functions addOptionInfo = Functions.AddOptionInfoFunction("素材测试图片", "test", "素材测试,图片文件", Const.CategoryImage, "jpg");
//        functionsList.add(addOptionInfo);
//
//        VodUploadMaterialRequest vodUploadMaterialRequest = VodUploadMaterialRequest.newBuilder()
//                .setSpaceName(space)
//                .setFilePath(filePath)
//                .setFileType(Const.FileTypeImage)
//                .setFileName("hello/vod/image.jpg")
//                .setFunctions(JSON.toJSONString(functionsList))
//                .build();
//
//        try {
//            VodCommitUploadInfoResponse vodCommitUploadInfoResponse = vodService.uploadMaterial(vodUploadMaterialRequest,null);
//            if (vodCommitUploadInfoResponse.getResponseMetadata().hasError()) {
//                System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getError());
//                System.exit(-1);
//            }
//            System.out.println(vodCommitUploadInfoResponse.toString());
//            System.out.println(vodCommitUploadInfoResponse.getResult().getData().getMid());
//            System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getRequestId());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

////    字幕素材上传
//    public static void main(String[] args) {
//        IVodService vodService = VodServiceImpl.getInstance();
//
//        // Configure your Access Key ID (AK) and Secret Access Key (SK) in the environment variables or in the local ~/.volc/config file. For detailed instructions, see https://www.volcengine.com/docs/4/65641.
//        // The SDK will automatically fetch the AK and SK from the environment variables or the ~/.volc/config file as needed.
//        // During testing, you may use the following code snippet. However, do not store the AK and SK directly in your project code to prevent potential leakage and safeguard the security of all resources associated with your account.
//        vodService.setAccessKey("your ak");
//        vodService.setSecretKey("your sk");
//
//        String space = "your space name";
//        String filePath = "your file path";
//
//        List<Functions> functionsList = new ArrayList<>();
//        Functions getMetaFunc = Functions.GetMetaFunction();
//        functionsList.add(getMetaFunc);
//
//        Functions snapShotFunc = Functions.SnapShotFunction(2.3);
//        functionsList.add(snapShotFunc);
//
//        Functions addOptionInfo = Functions.AddOptionInfoFunction("素材测试字幕", "test", "素材测试,字幕文件", Const.CategorySubtitle, "vtt");
//        functionsList.add(addOptionInfo);
//
//        VodUploadMaterialRequest vodUploadMaterialRequest = VodUploadMaterialRequest.newBuilder()
//                .setSpaceName(space)
//                .setFilePath(filePath)
//                .setFileType(Const.FileTypeObject)
//                .setFileName("hello/vod/object.vtt")
//                .setFunctions(JSON.toJSONString(functionsList))
//                .build();
//
//        try {
//            VodCommitUploadInfoResponse vodCommitUploadInfoResponse = vodService.uploadMaterial(vodUploadMaterialRequest,null);
//            if (vodCommitUploadInfoResponse.getResponseMetadata().hasError()) {
//                System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getError());
//                System.exit(-1);
//            }
//            System.out.println(vodCommitUploadInfoResponse.toString());
//            System.out.println(vodCommitUploadInfoResponse.getResult().getData().getMid());
//            System.out.println(vodCommitUploadInfoResponse.getResponseMetadata().getRequestId());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

}

URL 批量拉取上传

接口请求参数和返回参数说明详见 UploadMediaByUrl

package com.volcengine.example.vod.upload;

import com.volcengine.service.vod.IVodService;
import com.volcengine.service.vod.impl.VodServiceImpl;
import com.volcengine.service.vod.model.business.VodUploadTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VodUploadMediaByUrlDemo {

    public static void main(String[] args) throws Exception {
        // Create a VOD instance in the specified region.
        // IVodService vodService = VodServiceImpl.getInstance("cn-north-1");
        IVodService vodService = VodServiceImpl.getInstance();

        // Configure your Access Key ID (AK) and Secret Access Key (SK) in the environment variables or in the local ~/.volc/config file. For detailed instructions, see https://www.volcengine.com/docs/4/65641.
        // The SDK will automatically fetch the AK and SK from the environment variables or the ~/.volc/config file as needed.
        // During testing, you may use the following code snippet. However, do not store the AK and SK directly in your project code to prevent potential leakage and safeguard the security of all resources associated with your account.
        // vodService.setAccessKey("your ak");
        // vodService.setSecretKey("your sk");

        try {
            com.volcengine.service.vod.model.request.VodUrlUploadRequest.Builder reqBuilder = com.volcengine.service.vod.model.request.VodUrlUploadRequest.newBuilder();
                        reqBuilder.setSpaceName("your space");
                        com.volcengine.service.vod.model.business.VodUrlUploadURLSet.Builder uRLSetsBuilder = com.volcengine.service.vod.model.business.VodUrlUploadURLSet.newBuilder();
                        uRLSetsBuilder.setSourceUrl("");
            uRLSetsBuilder.setStorageClass(0);
            uRLSetsBuilder.setFileExtension(".mp4");
            uRLSetsBuilder.setCallbackArgs("my java callback args");
            Map<String, String> customUrlHeaders = new HashMap<>();
            customUrlHeaders.put("your header key", "your header value");
            uRLSetsBuilder.putAllCustomURLHeaders(customUrlHeaders);
            VodUploadTemplate impTemplate = VodUploadTemplate.newBuilder()
                    .addTemplateIds("imp template id")
                    .setTemplateType("imp")
                    .build();
            VodUploadTemplate transcodeTemplate = VodUploadTemplate.newBuilder()
                    .addTemplateIds( "transcode template id")
                    .setTemplateType("transcode")
                    .build();
            uRLSetsBuilder.addTemplates(impTemplate);
            uRLSetsBuilder.addTemplates(transcodeTemplate);
            reqBuilder.addURLSets(uRLSetsBuilder);

            com.volcengine.service.vod.model.response.VodUrlUploadResponse resp = vodService.uploadMediaByUrl(reqBuilder.build());
            if (resp.getResponseMetadata().hasError()) {
                System.out.println(resp.getResponseMetadata().getError());
                System.exit(-1);
            }
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

查询 URL 批量上传任务状态

接口请求参数和返回参数说明详见 QueryUploadTaskInfo

package com.volcengine.example.vod.upload;

import com.volcengine.service.vod.IVodService;
import com.volcengine.service.vod.impl.VodServiceImpl;
public class VodQueryUploadTaskInfoDemo {

    public static void main(String[] args) throws Exception {
        // Create a VOD instance in the specified region.
        // IVodService vodService = VodServiceImpl.getInstance("cn-north-1");
        IVodService vodService = VodServiceImpl.getInstance();

        // Configure your Access Key ID (AK) and Secret Access Key (SK) in the environment variables or in the local ~/.volc/config file. For detailed instructions, see https://www.volcengine.com/docs/4/65641.
        // The SDK will automatically fetch the AK and SK from the environment variables or the ~/.volc/config file as needed.
        // During testing, you may use the following code snippet. However, do not store the AK and SK directly in your project code to prevent potential leakage and safeguard the security of all resources associated with your account.
        // vodService.setAccessKey("your ak");
        // vodService.setSecretKey("your sk");

        try {
            com.volcengine.service.vod.model.request.VodQueryUploadTaskInfoRequest.Builder reqBuilder = com.volcengine.service.vod.model.request.VodQueryUploadTaskInfoRequest.newBuilder();
                        reqBuilder.setJobIds("your JobIds");
                        
            com.volcengine.service.vod.model.response.VodQueryUploadTaskInfoResponse resp = vodService.queryUploadTaskInfo(reqBuilder.build());
            if (resp.getResponseMetadata().hasError()) {
                System.out.println(resp.getResponseMetadata().getError());
                System.exit(-1);
            }
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上传进度条

进度条功能用于展示点播媒资上传的进度,您可根据自身业务需求使用进度条功能。进度条功能采用观察者模式,您可以通过实现 VodUploadProgressListener 接口中的 progressChanged() 方法集成相应的业务逻辑。

说明

使用进度条功能需要将 Java SDK 升级为大于等于 v1.0.97 的版本。

事件源支持的 EventType

EventType 名称

说明

FILE_SIZE_EVENT

文件大小事件通知。获得文件大小时会触发该事件,通知文件大小。

UPLOAD_BYTES_EVENT

传输事件通知。每个分片传输完成时会触发该事件,通知写入的分片字节数。

示例代码如下所示。

package com.volcengine.helper;

// 使用进度条,需要实现 VodUploadProgressListener 方法
public class VodUploadMediaProcessListener implements VodUploadProgressListener {
    /**
     * 已成功上传总字节数
     */
    private long bytesUploaded = 0;
    /**
     * 原文件大小
     */
    private long fileSize = -1;

    // 使用进度条需要您重写回调方法,以下为参考示例
    @Override
    public void progressChanged(VodUploadProgressEvent progressEvent) {
        long bytes = progressEvent.getByteSize();
        VodUploadProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            // 文件大小事件通知,获得文件大小时会触发该事件,通知文件大小
            case FILE_SIZE_EVENT:
                this.fileSize = bytes;
                // business logic ....
                System.out.println("file size is " + this.fileSize);
                break;
            // 传输事件通知,每个分片传输完成时会触发该事件,通知写入的分片字节数
            case UPLOAD_BYTES_EVENT:
                this.bytesUploaded += bytes;
                if (this.bytesUploaded != this.fileSize - 1) {
                    int percent = (int) (this.bytesUploaded * 100.0 / this.fileSize);
                    System.out.println("uploaded " + percent + "%");
                } else {
                    int percent = 99;
                    System.out.println("uploaded " + percent + "%");
                }
                // business logic ....
                break;
            default:
                break;
        }
    }
}