文件上传(支持断点续传/大文件切片上传)

时间:2022-08-28 20:23:48

参考地址(http://blog.csdn.net/zph1234/article/details/50577885
下面是实际使用demo

前台代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>上传文件</title>
    <script src="/js/jquery-1.8.2.min.js"></script>
</head>
<body>
<div id="drop_area" style="border:3px dashed silver;width:300px; height:200px">
    将文件拖拽到此<br/>(您的文件名请勿重复!)
</div>
<progress value="0" max="10" id="prouploadfile" style="width:300px;"></progress>
<span id="persent">0%</span>
<br/><br/>
<button onclick="stopup()" id="stop" style="width:100px; margin-left:100px;">上传</button>
<script> //拖拽上传开始 //-1.禁止浏览器打开文件行为 //拖离 document.addEventListener("drop",function(e){ e.preventDefault(); }) //拖后放 document.addEventListener("dragleave",function(e){ e.preventDefault(); }) //拖进 document.addEventListener("dragenter",function(e){ e.preventDefault(); }) //拖来拖去 document.addEventListener("dragover",function(e){ e.preventDefault(); }) //上传进度 var pro = document.getElementById('prouploadfile'); var persent = document.getElementById('persent'); function clearpro(){ pro.value=0; persent.innerHTML="0%"; } //2.拖拽 var stopbutton = document.getElementById('stop'); var resultfile=""; //拖拽区域 var box = document.getElementById('drop_area'); box.addEventListener("drop",function(e){ //获取文件对象 var fileList = e.dataTransfer.files; //检测是否是拖拽文件到页面的操作 if(fileList.length == 0){ return false; } //拖拉图片到浏览器,可以实现预览功能 //规定视频格式 in_array Array.prototype.S=String.fromCharCode(2); Array.prototype.in_array=function(e){ var r=new RegExp(this.S+e+this.S); return (r.test(this.S+this.join(this.S)+this.S)); }; var video_type=["video/mp4","video/ogg"]; //创建一个url连接,供src属性引用 var fileurl = window.URL.createObjectURL(fileList[0]); //如果是图片 if(fileList[0].type.indexOf('image') === 0){ var str="<img width='200px' height='200px' src='"+fileurl+"'>"; document.getElementById('drop_area').innerHTML=str; //如果是规定格式内的视频 }else if(video_type.in_array(fileList[0].type)){ var str="<video width='200px' height='200px' controls='controls' src='"+fileurl+"'></video>"; document.getElementById('drop_area').innerHTML=str; }else{ //其他格式,输出文件名 var str="文件名字:"+fileList[0].name; document.getElementById('drop_area').innerHTML=str; } resultfile = fileList[0]; //切片计算 filesize= resultfile.size; setsize=1000*1024; filecount = filesize/setsize; //定义进度条 pro.max=parseInt(Math.ceil(filecount)); i =getCookie(resultfile.name); i = (i!=null && i!="")?parseInt(i):0 if(Math.floor(filecount)<i){ alert("该文件已经上传完成,请勿重复上传!"); pro.value=i+1; persent.innerHTML="100%"; }else{ pro.value=i; p=parseInt(i)*100/Math.ceil(filecount) persent.innerHTML=parseInt(p)+"%"; } },false); //3.ajax上传 var stop=1; function xhr2(){ if(stop==1){ return false; } if(resultfile==""){ alert("请选择文件!") return false; } i=getCookie(resultfile.name); i = (i!=null && i!="")?parseInt(i):0 if(Math.floor(filecount)<parseInt(i)){ alert("已经上传完成!"); return false; } var xhr = new XMLHttpRequest();//第一步 //新建一个FormData对象 var formData = new FormData(); //追加文件数据 //改变进度条 pro.value=i+1; p=parseInt(i+1)*100/Math.ceil(filecount) persent.innerHTML=parseInt(p)+"%"; //进度条 if((filesize-i*setsize)>setsize){ blobfile= resultfile.slice(i*setsize,(i+1)*setsize); }else{ blobfile= resultfile.slice(i*setsize,filesize); formData.append('lastone', Math.floor(filecount)); } formData.append('file', blobfile); formData.append('blobname', i); formData.append('filename', resultfile.name); //设置响应返回的数据格式 //post方式 xhr.open('POST', '/document/addTempleteNew_dd'); //第二步骤 //发送请求 xhr.send(formData); //第三步骤 stopbutton.innerHTML = "暂停" //ajax返回 xhr.onreadystatechange = function(){ //第四步 if ( xhr.readyState == 4 && xhr.status == 200 ) { //请求成功 //console.log(xhr.responseText); if(i<filecount){ xhr2(); }else{ i=0; } if(xhr.responseText!="not end"){ window.parent.$('#affixdiv').after(xhr.responseText); }else{ console.log('正在分片上传中('+Math.floor(filecount)+')...'+i); } } }; //设置超时时间 xhr.timeout = 20000; xhr.ontimeout = function(event){ alert('请求超时,网络拥堵!\n(如果文件已经上传完成,请忽略此消息!)'); } i=i+1; setCookie(resultfile.name,i,1);//1天 } //设置cookie function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()+";path=/"); } //获取cookie function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } function stopup(){ if(stop==1){ stop = 0 xhr2(); }else{ stop = 1; stopbutton.innerHTML = "继续"; } } </script>
</body>
</html>

后台代码【PHP】

     <?php
        header("Content-type: text/html; charset=utf-8");
        $uid=$this->info['id'];
        $UpdType = array('gif', 'jpg', 'jpeg', 'png', 'bmp','swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid','doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf', 'mp4', 'rm', 'rmvb', 'asf', 'mkv', 'mpg', 'mepg', '3gp', 'ogg');
        if ($_POST) {
            $filename=iconv('utf-8','gbk',$_POST['filename']);
            $fileTypes =explode(".",$filename);
            $updFileExt = strtolower($fileTypes[count($fileTypes)-1]);
            if(!in_array($updFileExt,$UpdType)) die('此类型不允许上传至服务器!');
            $dir=$_SERVER['DOCUMENT_ROOT']."/uploads_file_pices/".$uid.'/'.md5($filename);
            $dir_complete_file_dir=$_SERVER['DOCUMENT_ROOT'].'/uploads_complete_file';
            if(!file_exists($dir)){
                mkdir($dir,0777,true);
            }
            if(!file_exists($dir_complete_file_dir)){
                mkdir($dir_complete_file_dir,0777,true);
            }
            $path=$dir."/".$_POST['blobname'];
            move_uploaded_file($_FILES["file"]["tmp_name"],$path);
            if(isset($_POST['lastone'])){
                $count=$_POST['lastone'];
                $fp = fopen($dir_complete_file_dir.'/'.$filename,"abw");
                for($i=0;$i<=$count;$i++){
                    $handle = fopen($dir."/".$i,"rb");
                    fwrite($fp,fread($handle,filesize($dir."/".$i)));
                    fclose($handle);
                    @unlink($_SERVER['DOCUMENT_ROOT'].'/'.$dir."/".$i);//删除文件
                }
                @rmdir($_SERVER['DOCUMENT_ROOT'].'/'.$dir);//删除文件夹
                fclose($fp);
                //资源路径
                list($usec, $sec) = explode(' ',microtime());
                $ymd  = date('YmdHis', (string)$sec);
                $usec = substr((string)$usec, 2);
                $microSenond =$ymd.$usec;
                $newFileName = $microSenond . '.' . $updFileExt ;
                $fileStorgePath_dir = $_SERVER['DOCUMENT_ROOT'].'/file/upload'.'/'.date('Y-m', time()).'/'.date('d', time());
                $fileStorgePath = '/file/upload'.'/'.date('Y-m', time()).'/'.date('d', time()).'/'.$newFileName;
                if(!file_exists($fileStorgePath_dir)){
                    mkdir($fileStorgePath_dir,0777,true);
                }
                $copy=copy($dir_complete_file_dir.'/'.$filename,$_SERVER['DOCUMENT_ROOT'].$fileStorgePath); //拷贝到新目录
                if($copy){
                    @unlink($dir_complete_file_dir.'/'.$filename); //删除旧目录下的文件
                    echo 'OK';
                }else{
                    die('文件转移失败!');
                }
            }else{
                echo 'NO';
            }
        }