分片上传大视频文件

2019-11-29  本文已影响0人  皮蛋馅儿

引入css

 <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

html部分

<div style="width: 30%; margin-top: 20px">
    <form action="" enctype="multipart/form-data">
        <input type="file" id="file" name="file" accept=".mp4,.mp3">
        <button class="btn btn-success" id="uploadBtn" type="button">开始上传</button>
    </form>
    <div class="progress progress-striped active" style="margin-top: 10px;">
        <div id="video-profess" style="width: 0" aria-valuemax="100" aria-valuemin="0" aria-valuenow="0" role="progressbar" class="progress-bar progress-bar-danger">
            <span class="sr-only">40% Complete (success)</span>
        </div>
    </div>
</div>

js部分

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
    // 点击开始上传视频
    $("#uploadBtn").click(function () {
        var file = $("#file")[0].files;
        if (file.length <= 0) {
            return alert('请选择视频');
        }
        $(this).attr("disabled", true);
        var time = new Date().getTime().toString();
        // 按时间戳重命名(防止同个文件不断累加内容)
        var newFile = new File([file[0]], time + file[0].name, {type: file[0].type});
        upload(newFile, 1);
    });

    // 分片上传视频
    var upload = function (file, num) {
        var formData = new FormData();
        var blockSize = 2 * 1024 * 1000; // 每次2M
        var blockNum = Math.ceil(file.size / blockSize);
        var nextSize = Math.min(num * blockSize, file.size);
        var fileData = file.slice((num - 1) * blockSize, nextSize);
        formData.append("file", fileData);
        formData.append("filename", file.name);
        $.ajax({
            url: "upload.php",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                if (response.code === 0) {
                    $('#video-profess').width((num * 100) / blockNum + '%');
                    if (file.size <= nextSize) {
                        alert('上传成功');
                        console.log(response.url)
                        $("#uploadBtn").removeAttr("disabled");
                        return;
                    }
                    upload(file, ++num);//递归调用
                } else {
                    alert('上传失败');
                }
            }
        });
    };
</script>

upload.php

<?php

header('Content-type: application/json');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
if (empty($_FILES) || !isset($_FILES['file'])) {
    exit(json_encode(['code' => -1, 'msg' => '请上传视频'], JSON_UNESCAPED_UNICODE));
}

$filename = $_POST['filename'];
$file = $_FILES['file'];

if ($file['error'] != 0) {
    exit(json_encode(['code' => -1, 'msg' => '请上传视频'], JSON_UNESCAPED_UNICODE));
}
$data = file_put_contents(__DIR__ . $filename, file_get_contents($file['tmp_name']), FILE_APPEND);
exit(json_encode(['code' => 0, 'msg' => 'success', 'data' => $data, 'url' => $filename], JSON_UNESCAPED_UNICODE));

加我微信公众号【皮蛋馅儿】,一起学习哦~

上一篇下一篇

猜你喜欢

热点阅读