Javascript 对接阿里云视频API

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>视频上传</title>
    <script src="~/Scripts/HRScript/Video/aliyun/jquery.min.js"></script>
    <script src="~/Scripts/HRScript/Video/aliyun/aliyun-upload-sdk-1.5.0.min.js"></script>
    <script src="~/Scripts/HRScript/Video/aliyun/es6-promise.min.js"></script>
    <script src="~/Scripts/HRScript/Video/aliyun/aliyun-oss-sdk-5.3.1.min.js"></script>
    <style type="text/css">
        .container {
            /*width: 1200px;*/
            margin: 0 auto;
        }
        .input-control {
            margin: 5px 0;
        }
            .input-control label {
                font-size: 14px;
                color: #333;
                width: 30%;
                text-align: right;
                display: inline-block;
                vertical-align: middle;
                margin-right: 10px;
            }
            .input-control input {
                width: 30%;
                height: 30px;
                padding: 0 5px;
            }
        .upload {
            padding: 30px 50px;
            color: #666;
        }
            .upload > div:nth-child(2) {
                margin: 20px 0;
            }
        .progress {
            font-size: 14px;
            padding-left: 20px;
        }
            .progress i {
                font-style: normal;
            }
        .upload-type {
            font-size: 12px;
            padding: 10px 0;
        }
            .upload-type button {
                padding: 10px 20px;
                background: #002868;
                border: none;
                outline: none;
                color: #fff;
            }
        .status {
            font-size: 14px;
            padding: 20px 0;
        }
 
        .info {
            font-size: 14px;
            padding-left: 30px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="upload">
            <div>
                <input type="file" id="fileUpload">
            </div>
            <div>
                <label class="status">上传状态: <span id="status"></span></label>
            </div>
            <div class="upload-type">
                <button id="authUpload" disabled="true">开始上传</button>
                @*<button id="pauseUpload" disabled="true">暂停</button>
                    <button id="resumeUpload" disabled="true">恢复上传</button>*@
                <span class="progress">上传进度: <i id="auth-progress">0</i> %</span>
                @*<input type="hidden" name="VId" id="VId" value="@ViewBag.VId" />*@
                <input type="hidden" name="Tittle" id="Tittle" value="@ViewBag.Tittle" />
            </div>
        </div>
    </div>
    <script>
        var APIAliPayPath = "http://192.168.30.115:9011/";
        //var APIAliPayPath = "http://demo.hrflag.com/WebAPIAliPlay/";
        //var APIAliPayPath = "https://form.hrflag.com/WebAPIAliPlay/";
        //兼容IE11
        if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function (fileData) {
                var binary = "";
                var pt = this;
                var reader = new FileReader();
                reader.onload = function (e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    //pt.result  - readonly so assign binary
                    pt.content = binary;
                    pt.onload()
                }
                reader.readAsArrayBuffer(fileData);
            }
        }
        $(document).ready(function () {
            /**
             * 创建一个上传对象
             * 使用 UploadAuth 上传方式
             */
            function createUploader() {
                var uploader = new AliyunUpload.Vod({
                    timeout: 60000,
                    partSize: 1048576,
                    parallel: 5,
                    retryCount: 3,
                    retryDuration: 2,
                    region: "cn-shanghai",
                    userId: "1643130352699306",
                    // 添加文件成功
                    addFileSuccess: function (uploadInfo) {
                        $('#authUpload').attr('disabled', false)
                        $('#resumeUpload').attr('disabled', false)
                        $('#status').text('添加文件成功, 等待上传...')
                    },
                    // 开始上传
                    onUploadstarted: function (uploadInfo) {
                        var Tittle = $("#Tittle").val();
                        if (!uploadInfo.videoId) {
                            var createUrl = APIAliPayPath + "AliVideo/GetUploadVideo?Title=" + Tittle + "&FileName=" + uploadInfo.file.name;
                            $.get(createUrl, function (data) {
                                var uploadAuth = data.UploadAuth;
                                var uploadAddress = data.UploadAddress
                                var videoId = data.VideoId
                                window.parent.videoId = videoId;
                                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
                            }, 'json')
                            $('#status').text('文件开始上传...')
                            //console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
                        } else {
                            // 如果videoId有值,根据videoId刷新上传凭证
                            var refreshUrl = APIAliPayPath + "AliVideo/RefreshUploadVideo?Vid=" + uploadInfo.videoId;
                            $.get(refreshUrl, function (data) {
                                var uploadAuth = data.UploadAuth
                                var uploadAddress = data.UploadAddress
                                var videoId = data.VideoId
                                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
                            }, 'json')
                        }
                    },
                    // 文件上传成功
                    onUploadSucceed: function (uploadInfo) {
                        console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
                        $('#status').text('文件上传成功!')
                    },
                    // 文件上传失败
                    onUploadFailed: function (uploadInfo, code, message) {
                        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
                        $('#status').text('文件上传失败!')
                    },
                    // 取消文件上传
                    onUploadCanceled: function (uploadInfo, code, message) {
                        console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
                        $('#status').text('文件上传已暂停!')
                    },
                    // 文件上传进度,单位:字节, 可以在这个函数中拿到上传进度并显示在页面上
                    onUploadProgress: function (uploadInfo, totalSize, progress) {
                        console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
                        var progressPercent = Math.ceil(progress * 100)
                        $('#auth-progress').text(progressPercent)
                        $('#status').text('文件上传中...')
                    },
                    // 上传凭证超时
                    onUploadTokenExpired: function (uploadInfo) {
                        // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
                        // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
                        // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
                        $('#status').text('文件上传超时!')
                        let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
                        $.get(refreshUrl, function (data) {
                            var uploadAuth = data.UploadAuth
                            uploader.resumeUploadWithAuth(uploadAuth)
                            console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
                        }, 'json')
                    },
                    // 全部文件上传结束
                    onUploadEnd: function (uploadInfo) {
                        $('#status').text('文件上传完毕!')
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                        //console.log("onUploadEnd: uploaded all the files")
                    }
                })
                return uploader
            }
 
            var uploader = null
 
            $('#fileUpload').on('change', function (e) {
                var file = e.target.files[0]
                if (!file) {
                    alert("请先选择需要上传的文件!")
                    return
                }
                var Title = file.name
                var userData = '{"Vod":{}}'
                if (uploader) {
                    uploader.stopUpload()
                    $('#auth-progress').text('0')
                    $('#status').text("")
                }
                uploader = createUploader()
                // 首先调用 uploader.addFile(event.target.files[i], null, null, null, userData)
                console.log(uploader)
                uploader.addFile(file, null, null, null, userData)
                $('#authUpload').attr('disabled', false)
                $('#pauseUpload').attr('disabled', true)
                $('#resumeUpload').attr('disabled', true)
            })
 
            // 第一种方式 UploadAuth 上传
            $('#authUpload').on('click', function () {
                // 然后调用 startUpload 方法, 开始上传
                if (uploader !== null) {
                    uploader.startUpload()
                    $('#authUpload').attr('disabled', true)
                    $('#pauseUpload').attr('disabled', false)
                }
            })
 
            // 暂停上传
            $('#pauseUpload').on('click', function () {
                if (uploader !== null) {
                    uploader.stopUpload()
                    $('#resumeUpload').attr('disabled', false)
                    $('#pauseUpload').attr('disabled', true)
                }
            })
 
 
            $('#resumeUpload').on('click', function () {
                if (uploader !== null) {
                    uploader.startUpload()
                    $('#resumeUpload').attr('disabled', true)
                    $('#pauseUpload').attr('disabled', false)
                }
            })
 
        })
        function uuid() {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";
 
            var uuid = s.join("");
            return uuid;
        }
    </script>
</body>
</html>
posted @ 2020-06-22 11:10  徐鲜  阅读(205)  评论(0编辑  收藏  举报