php 上传视频(分片)

分片上传视频,网上部分博客总结的使用方法模糊不清楚,自己总结的小demo,亲测可用!粘贴代码即可使用!不懂的可以留言!大家一起讨论!

index.html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #progress{
            width: 300px;
            height: 20px;
            background-color:#f7f7f7;
            box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);
            border-radius:4px;
            background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);
        }

        .finish{
            background-color: #149bdf;
            background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);
            background-size:40px 40px;
            height: 100%;
        }
        form{
            margin-top: 50px;
        }
    </style>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
    
<div id="progress">
    <div id="finish_video" class="finish" style="width: 0%;" progress="0"></div>
    <input type="hidden" name="VideoName" id="VideoName">
</div>
<div class="btn-group">
    <input id="video_file" type="file" class="file-input" style="visibility: hidden">
    <span class="btn btn-info btn-upload" style="float:left;" onclick="$(this).prev('input').trigger('click'); ">上传视频</span>
</div>

<script>
    //分片上传
    //上传视频
    var fileNameTime = Date.parse(new Date())/1000;

    var video_file = document.getElementById("video_file");
    var jdt_s = document.getElementById('finish_video');
    var ipt_s = $('#VideoName');
    var video_upload = new Upload(jdt_s,ipt_s);
    video_file.onchange = function(){
        fileNameTime = fileNameTime+1;
        video_upload.addFileAndSend(this);
    };

    function Upload(jdt,ipt){
        const LENGTH = 1024 * 1024;
        var start = 0;
        var end = start + LENGTH;
        var blob;
        var blob_num = 1;
        var is_stop = 0;
        //对外方法,传入文件对象
        this.addFileAndSend = function(that){
            var file = that.files[0];
            blob = cutFile(file);
            sendFile(blob,file);
            blob_num  += 1;
        };
        //切割文件
        function cutFile(file){
            var file_blob = file.slice(start,end);
            start = end;
            end = start + LENGTH;
            return file_blob;
        }
        //发送文件
        function sendFile(blob,file){
            var xhr = new XMLHttpRequest();
            var form_data = new FormData();
            var total_blob_num = Math.ceil(file.size / LENGTH);
            form_data.append('file',blob);
            form_data.append('blob_num',blob_num);
            form_data.append('total_blob_num',total_blob_num);
            form_data.append('file_name',fileNameTime+file.name.substr(file.name.lastIndexOf(".")));

            //xhr.open('POST','http://lh/sp/index.php',false); //上传文件的路径
            xhr.open('POST','http://lh/sp/index.php',false);
            xhr.onreadystatechange  = function () {
                var progress;
                var progressObj = jdt;
                if(total_blob_num == 1){
                    progress = '100%';
                }else{
                    progress = Math.min(100,(blob_num/total_blob_num)* 100 ) +'%';
                }
                progressObj.style.width = progress;
                progressObj.innerHTML=progress;
                var t = setTimeout(function(){
                    if(start < file.size && is_stop === 0){
                        blob = cutFile(file);
                        sendFile(blob,file);
                        blob_num  += 1;
                    }else{
                        var responsePath = xhr.responseText;
                        var firstPath = responsePath.indexOf("{");
                        var lastPath = responsePath.indexOf("}");
                        var pathReturn = responsePath.substr(firstPath,lastPath-firstPath+1);
                        var pathReturnObj = eval('(' + pathReturn + ')');
                        ipt.val(pathReturnObj.file_path);
                        alert('上传成功');
                        xhr = undefined;
                        form_data = undefined;
                    }
                },1000);
            };
            xhr.send(form_data);
        }
    }

</script>

    
</body>
</html>

index.php部分

<?php 

class UploadService
{
    private $filepath;
    private $tmpPath;  //PHP文件临时目录
    private $blobNum; //第几个文件块
    private $totalBlobNum; //文件块总数
    private $fileName; //文件名
    private $savePath; //保存路径
    private $basePath;

    public function __construct($type, $tmpPath,$blobNum,$totalBlobNum,$fileName){
        $this->tmpPath =  $tmpPath;
        $this->blobNum =  $blobNum;
        $this->totalBlobNum =  $totalBlobNum;
        $this->fileName =  $fileName;
        $this->savePath =  date('Ymd',mb_substr($fileName,0,10));
        $this->DataPath = date('Ymd',time());
        $this->filepath = __DIR__.'/public/uploads/'.$type .'/'.$this->DataPath.'/'; //提前建立 __DIR__ 目录 因为没有创建权限
        $this->basePath = __DIR__.'/public/uploads/'.$type;
    }

    //判断是否是最后一块,如果是则进行文件合成并且删除文件块
    private function fileMerge(){
        if($this->blobNum == $this->totalBlobNum){
            $blob = '';
            for($i=1; $i<= $this->totalBlobNum; $i++){
                $blob .= file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i);
            }
            file_put_contents($this->filepath.'/'. $this->fileName,$blob);
            $this->deleteFileBlob();
        }
    }

    //删除文件块
    private function deleteFileBlob(){
        for($i=1; $i<= $this->totalBlobNum; $i++){
            @unlink($this->filepath.'/'. $this->fileName.'__'.$i);
        }
    }

    //移动文件
    private function moveFile(){
        $this->touchDir();
        $filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;
        move_uploaded_file($this->tmpPath,$filename);
    }

    //API返回数据
    public function apiReturn(){
        if(!file_exists($this->basePath)){
            mkdir($this->basePath);
        }
        $this->moveFile();
        $this->fileMerge();
        if($this->blobNum == $this->totalBlobNum){
            if(file_exists($this->filepath.'/'. $this->fileName)){
                $data['code'] = 2;
                $data['msg'] = 'success';
    //$_SERVER['DOCUMENT_URI']=>$_SERVER['REQUEST_URI']
    //$data['file_path'] = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI']).str_replace('.','',$this->filepath).'/'. $this->fileName;
                $data['file_path'] = '/uploads/video/'.$this->DataPath.'/'.$this->fileName;
            }
        }else{
            if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){
                $data['code'] = 1;
                $data['msg'] = 'waiting for all';
                $data['file_path'] = '';
            }
        }
        header('Content-type: application/json');
        echo json_encode($data);
    }

    //建立上传文件夹
    private function touchDir(){
        if(!file_exists($this->filepath)){
            mkdir($this->filepath);
        }
    }

}

function cut_upload()
{   

    ini_set('memory_limit', '200M');
    //ini_set('memory_limit', '-1');//目前视频上传受 file_put_content()函数占用内存影响
    //实例化并获取系统变量传参
    $upload = new UploadService('video',$_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']);
    //调用方法,返回结果
    $upload->apiReturn();
}

cut_upload();

目录结构

image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容

  • JS分片上传 //分片上传 function ScarecrowPatchUpload (uploadPath, ...
    隐形的稻草人_44ca阅读 1,047评论 0 1
  • 本文参加又拍云原创技术征文活动 注册&实名认证 注册我就不说了,大家自行前往又拍云注册就行。 注册之后需要实名认证...
    Willis1阅读 519评论 0 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,454评论 16 22
  • 创业是很多人的梦想,多少人为了理想和不甘选择了创业来实现自我价值,我就是其中一个。 创业后,我由女人变成了超人,什...
    亦宝宝阅读 1,793评论 4 1
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,534评论 0 11