全部产品
Search
文档中心

视频点播:通过视频点播API上传媒体文件

更新时间:Jul 18, 2024

如需使用视频点播为音视频等媒体文件进行媒体处理(转码、审核、添加水印等)、分发播放等操作,则需要先将媒体文件上传到视频点播中。本文以Java SDK调用API为例介绍如何调用API上传媒体文件,并提供完整的API上传Demo供参考。

背景信息

通过视频点播API上传,实际是基于OSS原生SDK上传,需要开发者自行实现所有上传逻辑,包括在点播服务获取上传地址和凭证、Base64解码上传凭证和地址、以及调用OSS能力完成上传。此方式较为繁琐且出错率较高,因此,本文封装完整API上传Demo供开发者参考,以避免您在通过视频点播API上传时,出现媒资一直处于上传中的问题。

说明
  • 点播API上传是基于OSS的上传,更多上传原理请参见OSS上传概述

  • 本文以Java语言为例提供说明,其他语言可以参考代码逻辑自行实现,或参考基于OSS原生SDK上传

  • 更多咨询及建议,请加入服务钉钉群(群号:11370001915)获取技术支持。

前提条件

步骤一:安装点播服务端SDK

操作指引请参见点播Java SDK安装

步骤二:安装OSS SDK

操作指引请参见OSS Java SDK安装

步骤三:上传

以下代码示例展示了如何调用OSS能力来实现本地上传、网络流/网络URL上传、本地M3U8上传、分片上传以及断点续传,如何在点播服务获取上传地址和凭证、Base64解码上传凭证和地址等完整的上传示例请参见完整代码示例

本地上传

public static void uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, String localFile) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");

        try {
            File file = new File(localFile);
            PutObjectResult result = ossClient.putObject(bucketName, objectName, file);
            // 如果上传成功,则返回200。
            // 上传文件的同时指定进度条参数。此处UploadOss为调用类的类名,请在实际使用时替换为相应的类名。
//            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName,objectName, file).
//                    <PutObjectRequest>withProgressListener(new UploadOss()));
//            System.out.println(result.getResponse().getStatusCode());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

网络流、网络URL上传

public static void uploadURLFile(OSSClient ossClient, JSONObject uploadAddress, String url) {
    String bucketName = uploadAddress.getString("Bucket");
    String objectName = uploadAddress.getString("FileName");

    try {
        InputStream inputStream = new URL(url).openStream();
        PutObjectResult result = ossClient.putObject(bucketName, objectName, inputStream);
        // 如果上传成功,则返回200。
        System.out.println(result.getResponse().getStatusCode());
    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message:" + oe.getErrorMessage());
        System.out.println("Error Code:" + oe.getErrorCode());
        System.out.println("Request ID:" + oe.getRequestId());
        System.out.println("Host ID:" + oe.getHostId());
    } catch (Throwable ce) {
        System.out.println("Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message:" + ce.getMessage());
    } finally {
        // 关闭OSSClient。
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}

本地M3U8上传

说明

上传本地M3U8音视频文件(包括所有分片文件)到点播,需上传本地M3U8索引文件地址和所有分片地址。

public static void uploadLocalM3U8(OSSClient ossClient, JSONObject uploadAddress, String indexFile, String[] tsFiles ) {

        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
        String objectPrefix = uploadAddress.getString("ObjectPrefix");
        System.out.println(uploadAddress.toJSONString());

        try {
            //上传索引文件indexFile
            File index = new File(indexFile);
            ossClient.putObject(bucketName, objectName, index);
            Thread.sleep(200);
            //上传ts文件  tsFiles
            for(String filePath : tsFiles){
                File ts = new File(filePath);
                ossClient.putObject(bucketName, objectPrefix + ts.getName(), ts);
                Thread.sleep(200);
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

分片上传以及断点续传

public static void uploadEnableCheckPointFile(OSSClient ossClient, JSONObject uploadAddress, String localFile) {
    String bucketName = uploadAddress.getString("Bucket");
    String objectName = uploadAddress.getString("FileName");

    try {
        UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName,objectName);
        // 通过UploadFileRequest设置单个参数。
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.mp4。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
        uploadFileRequest.setUploadFile(localFile);
        // 指定上传并发线程数,默认值为1。
        uploadFileRequest.setTaskNum(5);
        // 指定上传的分片大小,单位为字节,取值范围为100 KB~5 GB。默认值为100 KB。
        uploadFileRequest.setPartSize(1 * 1024 * 1024);
        // 开启断点续传,默认关闭。
        uploadFileRequest.setEnableCheckpoint(true);
        // 记录本地分片上传结果的文件。上传过程中的进度信息会保存在该文件中,如果某一分片上传失败,再次上传时会根据文件中记录的点继续上传。上传完成后,该文件会被删除。
        // 如果未设置该值,默认与待上传的本地文件同路径,名称为${uploadFile}.ucp。
        //uploadFileRequest.setCheckpointFile("yourCheckpointFile");
        // 断点续传上传。
        ossClient.uploadFile(uploadFileRequest);

    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message:" + oe.getErrorMessage());
        System.out.println("Error Code:" + oe.getErrorCode());
        System.out.println("Request ID:" + oe.getRequestId());
        System.out.println("Host ID:" + oe.getHostId());
    } catch (Throwable ce) {
        System.out.println("Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message:" + ce.getMessage());
    } finally {
        // 关闭OSSClient。
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}

完整代码示例

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.InputStream;
import java.net.URL;

/**
 * *****   使用须知     ******!!
 * 以下Java示例代码演示了如何通过API 方式上传媒资文件至视频点播。OSS部分详细请参考 https://www.alibabacloud.com/help/object-storage-service/latest/overview-3
 * 此demo不同于上传SDK,如何使用上传SDK参考 https://www.alibabacloud.com/help/apsaravideo-for-vod/latest/upload-sdk-overview
 * <p>
 * 一、普通音视频上传
 *
 * 1.上传本地文件,使用分片上传,并支持断点续传。
 * 1.1 当断点续传关闭时,最大支持上传任务执行时间为3000秒,具体可上传文件大小与您的网络带宽及磁盘读写能力有关。 参见uploadEnableCheckPointFile函数。
 * 1.2 当断点续传开启时,最大支持48.8TB的单个文件,注意,断点续传开启后,上传任务执行过程中,同时会将当前上传位置写入本地磁盘文件,影响您上传文件的速度,请您根据文件大小选择是否开启
 *
 * 2.上传网络流,可指定文件URL进行上传,最大支持48.8TB的单个文件。参见uploadURLFile函数。
 *
 * 3.上传文件流,可指定本地文件进行上传,不支持断点续传,最大支持5GB的单个文件。参见uploadLocalFile函数。
 *
 * <p>
 * 二、m3u8文件上传:
 * 1.上传本地m3u8音视频文件(包括所有分片文件)到点播,需上传本地m3u8索引文件地址和所有分片地址。参见uploadLocalM3U8函数
 * 2.上传网络m3u8音视频文件建议使用URL方式。
 *
 * 注:
 * 1) 上传网络m3u8音视频文件时需要保证地址可访问,如果有权限限制,请设置带签名信息的地址,且保证足够长的有效期,防止地址无法访问导致上传失败
 * <p>
 *
 * 三、上传进度:
 * 1.默认上传进度回调函数:必须实现ProgressListener类,若不需要可不实现此类。参考 https://www.alibabacloud.com/help/object-storage-service/latest/upload-progress-bars-4;
 * 2.自定义上传进度回调函数:您可根据自已的业务场景重新定义不同事件处理的方式,只需要修改上传回调示例函数即可。
 * 3.本demo中,参见第 225 行代码示例
 *
 * <p>
 *
 * 四、接口说明:
 * 1.CreateUploadVideo 和 RefreshUploadVideo 都只是获取凭证的接口,根据业务需要二选一即可
 * 2.RefreshUploadVideo 可用于凭证超时后重新获取,也可用于覆盖文件上传,videoId保持不变
 * 3.CreateUploadImage  可用于获取图片上传凭证
 * 4.CreateUploadAttachedMedia  可用于获取辅助媒资上传凭证
 * 3.接口详细说明参考 https://www.alibabacloud.com/help/apsaravideo-for-vod/latest/api-doc-vod-2017-03-21-api-overview
 *
 * <p>
 *
 * 注意:
 * 请替换示例中的必选参数,示例中的可选参数如果您不需要设置,请将其删除,以免设置无效参数值与您的预期不符。
 */
public class UploadVodByApiDemo implements ProgressListener {

    //上传进度条相关参数,非必须
    private long bytesWritten = 0;
    private long totalBytes = -1;
    private boolean succeed = false;

    public static void main(String[] argv) {
        // 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
        // 本示例通过从环境变量中读取AccessKey,来实现API访问的身份验证。运行代码示例前,请配置环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        //需要上传到VOD的本地视频文件的完整路径,需要包含文件扩展名
        String localFile = "E:/demo/demo.mp4";
        // 填写网络流地址。可访问的url即可
        String url = "https://bucket-name*****.oss-cn-shanghai.aliyuncs.com/demo/demo.mp4";

        try {
            // 初始化VOD客户端并获取上传地址和凭证
            DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);

            //获取视频上传凭证
            CreateUploadVideoResponse createUploadVideoResponse = createUploadVideo(vodClient);
            //获取刷新上传凭证
            //RefreshUploadVideoResponse refreshUploadVideoResponse = refreshUploadVideo(vodClient);
            //获取图片上传凭证
            //CreateUploadImageResponse createUploadImageResponse = createUploadImage(vodClient);
            //获取辅助媒资上传凭证
            //CreateUploadAttachedMediaResponse createUploadAttachedMediaResponse = createUploadAttachedMedia(vodClient);

            // 执行成功会返回VideoId、UploadAddress和UploadAuth
            String videoId = createUploadVideoResponse.getVideoId();
            JSONObject uploadAuth = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAuth()));
            JSONObject uploadAddress = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAddress()));

            //使用UploadAuth和UploadAddress初始化OSS客户端
           // 通过这个OSSClient对象,传入uploadAuth和uploadAddress,即可完成视频文件到阿里云OSS的上传
            OSSClient ossClient = initOssClient(uploadAuth, uploadAddress);

            // 上传方式, 按需选择
            // 1.本地上传文件,注意是同步上传会阻塞等待,耗时与文件大小和网络上行带宽有关
            uploadLocalFile(ossClient, uploadAddress, localFile);
            // 2.网络文件上传
            //uploadURLFile(ossClient, uploadAddress, url);
            // 3.分片、断点续传
            //uploadEnableCheckPointFile(ossClient, uploadAddress, localFile);
            // 4.上传m3u8
            //String indexFile = "E:/demo/demo.m3u8";
            //String[] tsFiles = {"E:/demo/demo_01.ts"};
            //uploadLocalM3U8(ossClient, uploadAddress, indexFile, tsFiles);

            System.out.println("Put local file succeed, VideoId : " + videoId);
        } catch (Exception e) {
            System.out.println("Put local file fail, ErrorMessage : " + e.getLocalizedMessage());
        }
    }

    /**
     * 初始化VOD客户端
     * @throws ClientException
     */
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // 点播服务接入区域,中国内地请填cn-shanghai,其他区域请参考文档 https://www.alibabacloud.com/help/apsaravideo-for-vod/latest/vod-centers-and-endpoints
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    /**
     * 初始化OSS客户端
     * @throws ClientException
     */
    public static OSSClient initOssClient(JSONObject uploadAuth, JSONObject uploadAddress) {
        String endpoint = uploadAddress.getString("Endpoint");
        String accessKeyId = uploadAuth.getString("AccessKeyId");
        String accessKeySecret = uploadAuth.getString("AccessKeySecret");
        String securityToken = uploadAuth.getString("SecurityToken");
        return new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    }

    /**
     * 获取上传凭证
     * @throws ClientException
     */
    public static CreateUploadVideoResponse createUploadVideo(DefaultAcsClient vodClient) throws ClientException {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setFileName("vod_test.m3u8");
        request.setTitle("this is title");
        //request.setDescription("this is desc");
        //request.setTags("tag1,tag2");
        //request.setCoverURL("http://vod.****.com/test_cover_url.jpg");
        //request.setCateId(-1L);
        //request.setTemplateGroupId("34f055******c7af499c73");
        //request.setWorkflowId("");
        //request.setStorageLocation("");
        //request.setAppId("app-1000000");

        return vodClient.getAcsResponse(request);
    }

    /**
     * 获取刷新凭证
     * @throws ClientException
     */
    public static RefreshUploadVideoResponse refreshUploadVideo(DefaultAcsClient vodClient) throws ClientException {
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        request.setAcceptFormat(FormatType.JSON);
        request.setVideoId("VideoId");

        //设置请求超时时间
        request.setSysReadTimeout(1000);
        request.setSysConnectTimeout(1000);

        return vodClient.getAcsResponse(request);
    }

    /**
     * 获取图片上传凭证
     * @throws ClientException
     */
    public static CreateUploadImageResponse createUploadImage(DefaultAcsClient vodClient) throws ClientException {
        CreateUploadImageRequest request = new CreateUploadImageRequest();
        request.setImageType("default");
        request.setAcceptFormat(FormatType.JSON);

        //设置请求超时时间
        request.setSysReadTimeout(1000);
        request.setSysConnectTimeout(1000);

        return vodClient.getAcsResponse(request);
    }

    /**
     * 获取辅助媒资上传凭证
     * @throws ClientException
     */
    public static CreateUploadAttachedMediaResponse createUploadAttachedMedia(DefaultAcsClient vodClient) throws ClientException {
        CreateUploadAttachedMediaRequest request = new CreateUploadAttachedMediaRequest();
        request.setBusinessType("watermark");
        request.setMediaExt("png");
        request.setAcceptFormat(FormatType.JSON);

        //设置请求超时时间
        request.setSysReadTimeout(1000);
        request.setSysConnectTimeout(1000);

        return vodClient.getAcsResponse(request);
    }

    /**
     *  本地文件上传
     * @throws Exception
     */
    public static void uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, String localFile) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");

        try {
            File file = new File(localFile);
            PutObjectResult result = ossClient.putObject(bucketName, objectName, file);
            // 如果上传成功,则返回200。
            // 上传文件的同时指定进度条参数。此处UploadOss为调用类的类名,请在实际使用时替换为相应的类名。
//            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName,objectName, file).
//                    <PutObjectRequest>withProgressListener(new UploadOss()));
//            System.out.println(result.getResponse().getStatusCode());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     *  网络流式上传
     * @throws Exception
     */
    public static void uploadURLFile(OSSClient ossClient, JSONObject uploadAddress, String url) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");

        try {
            InputStream inputStream = new URL(url).openStream();
            PutObjectResult result = ossClient.putObject(bucketName, objectName, inputStream);
            // 如果上传成功,则返回200。
            System.out.println(result.getResponse().getStatusCode());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     *  断点续传上传
     * @throws Exception
     */
    public static void uploadEnableCheckPointFile(OSSClient ossClient, JSONObject uploadAddress, String localFile) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");

        try {
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName,objectName);
            // 通过UploadFileRequest设置单个参数。
            // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.mp4。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
            uploadFileRequest.setUploadFile(localFile);
            // 指定上传并发线程数,默认值为1。
            uploadFileRequest.setTaskNum(5);
            // 指定上传的分片大小,单位为字节,取值范围为100 KB~5 GB。默认值为100 KB。
            uploadFileRequest.setPartSize(1 * 1024 * 1024);
            // 开启断点续传,默认关闭。
            uploadFileRequest.setEnableCheckpoint(true);
            // 记录本地分片上传结果的文件。上传过程中的进度信息会保存在该文件中,如果某一分片上传失败,再次上传时会根据文件中记录的点继续上传。上传完成后,该文件会被删除。
            // 如果未设置该值,默认与待上传的本地文件同路径,名称为${uploadFile}.ucp。
            //uploadFileRequest.setCheckpointFile("yourCheckpointFile");
            // 断点续传上传。
            ossClient.uploadFile(uploadFileRequest);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     *  本地上传m3u8
     * @throws Exception
     */
    public static void uploadLocalM3U8(OSSClient ossClient, JSONObject uploadAddress, String indexFile, String[] tsFiles ) {

        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
        String objectPrefix = uploadAddress.getString("ObjectPrefix");
        System.out.println(uploadAddress.toJSONString());

        try {
            //上传索引文件indexFile
            File index = new File(indexFile);
            ossClient.putObject(bucketName, objectName, index);
            Thread.sleep(200);
            //上传ts文件  tsFiles
            for(String filePath : tsFiles){
                File ts = new File(filePath);
                ossClient.putObject(bucketName, objectPrefix + ts.getName(), ts);
                Thread.sleep(200);
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    // 使用进度条需要您重写回调方法,以下仅为参考示例。
    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                System.out.println("Start to upload......");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
                break;
            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 ratio: unknown" + "(" + this.bytesWritten + "/...)");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
                break;
            case TRANSFER_FAILED_EVENT:
                System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
                break;
            default:
                break;
        }
    }

    public static String decodeBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            Base64 decoder = new Base64();
            try {
                b = decoder.decode(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
            }
        }
        return result;
    }
}