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

本文为您介绍如何使用视频点播服务端 Java SDK 将音频、视频、图片等媒资文件上传至视频点播服务。

使用说明

  • 使用前,请确保您已充分了解视频点播产品的收费方式和价格。媒资上传到视频点播中会产生存储费用,具体参见媒资存储计费
  • 使用前,请确保您已阅读媒资上传概述了解媒资上传功能、视频点播支持的媒资类型、格式和大小限制。

前提条件

直接上传

视频点播服务端 SDK 封装了获取上传地址和凭证接口、确认上传接口以及上传逻辑,您只需简单配置即可进行上传。完整的上传流程请见服务端上传

说明

上传任务成功提交后,您可通过媒资上传完成事件通知获取任务结果。配置方式请见事件通知概述

上传音视频

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

接口请求参数和返回参数说明详见 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";

        // 上传功能函数,可用于实现截图、设置媒资信息、触发工作流进行转码等功能。详见[上传功能函数说明](https://www.volcengine.com/docs/4/1185644)
        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)
//                .setUploadHostPrefer("")
                .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))
//                .setUploadHostPrefer("")
                .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) {
//        // 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.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) {
//        // 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.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 批量拉取上传

视频点播服务端 SDK 封装了 URL 批量拉取上传接口,您只需简单配置即可进行上传。完整的上传流程请见服务端上传

说明

  • 本接口主要适用于文件没有存储在本地服务器或终端,需要通过公网访问的 URL 地址上传的场景。源文件 URL 支持 HTTP 和 HTTPS。
  • 本接口为异步上传接口。上传任务成功提交后,系统会生成异步执行的任务,排队执行,不保证时效性。
  • 本接口的请求参数和返回参数说明详见 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(1);
            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) {
            // 文件大小事件通知。SDK 获得文件大小时会触发该事件,通知文件大小
            case FILE_SIZE_EVENT:
                this.fileSize = bytes;
                // 业务逻辑
                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 + "%");
                }
                // 业务逻辑
                break;
            default:
                break;
        }
    }
}

其它示例

签发临时上传 Token

如果您使用客户端上传 SDK 进行上传,您需要在应用服务端通过 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));

    }
}

获取上传地址和凭证

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

package com.volcengine.example.vod.upload;

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

    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.VodApplyUploadInfoRequest.Builder reqBuilder = com.volcengine.service.vod.model.request.VodApplyUploadInfoRequest.newBuilder();
                        reqBuilder.setSpaceName("your SpaceName");
                        reqBuilder.setSessionKey("your SessionKey");
                        reqBuilder.setFileSize(0);
                        reqBuilder.setFileType("your FileType");
                        reqBuilder.setFileName("your FileName");
                        reqBuilder.setStorageClass(1);
                        reqBuilder.setFileExtension("your FileExtension");
                        reqBuilder.setClientNetWorkMode("your ClientNetWorkMode");
                        reqBuilder.setClientIDCMode("your ClientIDCMode");
                        reqBuilder.setNeedFallback(false);
                        reqBuilder.setUploadHostPrefer("your UploadHostPrefer");
                        
            com.volcengine.service.vod.model.response.VodApplyUploadInfoResponse resp = vodService.applyUploadInfo(reqBuilder.build());
            if (resp.getResponseMetadata().hasError()) {
                System.out.println(resp.getResponseMetadata().getError());
                System.exit(-1);
            }
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}