阿里云上传

2020-10-29  本文已影响0人  王二麻子88

阿里云上传

1. 导入阿里云上传SDK

<script src="/static/aliyun/aliyun-oss-sdk-5.3.1.min.js"></script>
<script src="/static/aliyun/aliyun-upload-sdk-1.5.0.min.js"></script>

2. 实例化阿里云

function initAliUpload() {
    const uploader = new AliyunUpload.Vod({
    timeout: $("#timeOut").val(),
    // 上传视频的切片大小
    partSize: $('#partSize').val(),
    // 上传视频的并行切片个数
    parallel: $('#parallel').val(),
    // 上传失败重新上传的次数
    retryCount: $('#retryCount').val(),
    // 上传失败重新上传的间隔
    retryDuration: $('#retryDuration').val(),
    // 上传到点播的地域
    region: $('#region').val(),
    // 阿里账号 Id
    userId: $('#userId').val(),
    // 监听添加文件成功
    addFileSuccess: function (uploadInfo) {
    // console.log("addFileSuccess: " + uploadInfo.file.name)
        layui.use("layer", function () {
            const layer = layui.layer;
            layer.msg("添加文件成功", {time: 2000})
        })
    },
    // 监听开始上传
    onUploadstarted: function (uploadInfo) {
        console.log(uploadInfo);
        // 如果videoId有值,根据videoId刷新上传凭证
        if (!uploadInfo.videoId) {
            var createUrl = '/front/aliyun/createUploadVideo';
            $.get(createUrl, function (data) {
                console.log(data);
                var uploadAuth = data.UploadAuth
                var uploadAddress = data.UploadAddress
                var videoId = data.VideoId
                videoId1 = data.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刷新上传凭证
            // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
            let refreshUrl = '/front/aliyun/refreshUploadVideo?videoId=' + uploadInfo.videoId;
            $.get(refreshUrl, function (data) {
                var uploadAuth = data.UploadAuth;
                var uploadAddress = data.UploadAddress;
                var videoId = data.VideoId;
                videoId1 = data.VideoId;
                // 设置作者以及地址
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
            }, 'json')
        }
    },
    // 文件上传成功
    onUploadSucceed: function (uploadInfo) {
        removeProgressBar();
        swal({
        type: "success",
        title: "文件上传成功"
        });
        console.log(uploadInfo);
        /*
        * bucket: "outin-dfc7aaae61c411eaa4b500163e1c60dc"
        checkpoint: {file: File, name: "sv/4623b628-1754f1852e6/4623b628-1754f1852e6.mp4", fileSize: 19894281, partSize: 1048576, uploadId: "042FEC8EDB694A87B0579696E8C0985A", …}
        endpoint: "https://oss-cn-shanghai.aliyuncs.com"
        file: File {name: "02-软件作用.mp4", lastModified: 1592538086119, lastModifiedDate: Fri Jun 19 2020 11:41:26 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 19894281, …}
        fileHash: "4a6bc5172f752b6688e9c98d9a028ea4"
        isImage: false
        loaded: 1
        object: "sv/4623b628-1754f1852e6/4623b628-1754f1852e6.mp4"
        region: "cn-shanghai"
        retry: false
        ri: "14962811-F028-4636-9926-8EC4A80D4D85"
        state: "Success"
        userData: "eyJWb2QiOnt9fQ=="
        videoId: "9d621624842646ae8219f80459a539ac"
        videoInfo: {}
        _bucket: null
        _endpoint: null
        _object: null
        * */
        // 获取 videoId
        // $("#videoId").val(uploadInfo.videoId).parent(".upload").next(".preview").html("已上传文件<br />" + uploadInfo.file.name);

        // 视频在线预览
        const getTpl = document.querySelector("#pdf-preview-tpl").innerHTML;
        layui.use("laytpl", function () {
        const laytpl = layui.laytpl;
        laytpl(getTpl).render({
            name: uploadInfo.file.name,
            type: "video"
        }, function (html) {                                                           $("#videoId").val(uploadInfo.videoId).parent(".upload").next(".preview").html(html).find(".delPdf").click(function(){
        $.ajax({
            url: "/deleteVideo",
            method: "POST",
            type: "POST",
            data: {
                VideoId :uploadInfo.videoId
            },
            success: function(res) {
                if (res.success) {
                    // 清除预览内容
                    $("#videoId").val("").parent(".upload").next(".preview").html("");
                    $("#cover").val("");
                } else {
                    layer.msg("视频删除失败", {time: 2500})
                }
            }
        })
        // 清除输入框内容
        });
            // 存取URL
            $("#cover").val(uploadInfo.object);
        })
    });


    },
    // 文件上传失败
    onUploadFailed: function (uploadInfo, code, message) {
        removeProgressBar();
        swal({
            type: "error",
            title: "文件上传失败"
        });
        console.log(uploadInfo);
    },
    // 取消文件上传
    onUploadCanceled: function (uploadInfo, code, message) {

    },
    // 文件上传进度,单位:字节, 可以在这个函数中拿到上传进度并显示在页面上
    onUploadProgress: function (uploadInfo, totalSize, progress) {
        $(".circleChart#progress-bar").circleChart({
            animate: 0,
            value: Math.ceil(progress * 100)
        })
    },
    // 上传凭证超时
    onUploadTokenExpired: function (uploadInfo) {

    },
    // 全部文件上传结束
    onUploadEnd: function (uploadInfo) {
        removeProgressBar()
        }
    });
    return uploader
}

3. 使用阿里云上传实例

const videoEl = document.querySelector("#videos");
videoEl.addEventListener("change", function (e) {
    const file = e.target.files[0];
    // console.log(file);
    if (!file) {
        return false
    }
    // console.log(file.size);
    let fileName = file.name;
    let fileType = file.type;
    let fileSize = file.size;
    if (fileType.indexOf("mp4") === -1) {
        swal({
            type: "error",
            title: "上传失败",
            text: "请上传MP4类型的视频文件"
        })
    } else if (fileSize > 102400000) {
        swal({
            type: "error",
            title: "上传失败",
            text: "文件必须小于100M"
        })
    } else {
        // 初始化 aliyun 上传
        // 获取背景图片和第一帧视频图片作为背景资源
        const videoUrl = URL.createObjectURL(file);
        const videoEl = document.querySelector("#parseVideo");
        let video, output;
        const scale = 1.0;
        videoEl.src = videoUrl;
        videoEl.oncanplaythrough = function (ele) {
            // console.log("视频的时长为: ");
            // console.log(videoEl.duration);
            var hour = parseInt((videoEl.duration) / 3600);
            var minute = parseInt((videoEl.duration % 3600) / 60);
            var second = Math.ceil(videoEl.duration % 60);
            // console.log("这段视频的时长为:"+hour+"小时,"+minute+"分,"+second+"秒");
            let durationStr = hour + ":" + minute + ":" + second;
            $("#videoDuration").val(durationStr)
        };
        const aliUploader = initAliUpload();
        const result = aliUploader.addFile(file, null, null, null, userData);  // 此处添加aliyun文件是一个同步的过程
        if (result) {
            // 开启自动上传
            aliUploader.startUpload();
            loadProgressBar();
        } else {
            swal({
                type: "error",
                title: "上传错误",
                text: "aliyun添加文件列表异常"
            })
        }
    }
});
上一篇下一篇

猜你喜欢

热点阅读