本文实例讲述了php大文件切割上传并带进度条功能。分享给大家供大家参考,具体如下:

前面一篇介绍了php大文件切割上传功能,这里再来进一步讲解php大文件切割上传并带进度条功能。

项目结构图:

14-slice-upload-fix.html文件:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>大文件切割上传带进度条</title>
  <link rel="stylesheet" href="">
<script>
var xhr = new xmlhttprequest();//xhr对象
var clock = null;
function selfile(){
  clock = window.setinterval(sendfile,1000);
}
var sendfile = (function (){
  const length = 1024 * 1024 * 10;//每次上传的大小
  var start = 0;//每次上传的开始字节
  var end = start + length;//每次上传的结尾字节
  var sending = false;//表示是否正在上传
  var fd = null;//创建表单数据对象
  var blob = null;//二进制对象
  var percent = 0;
  return (function (){
    //如果有块正在上传,则不进行上传
    if(sending == true){
      return;
    }
    var file = document.getelementsbyname('video')[0].files[0];//文件对象
    //如果sta>file.size,就结束了
    if(start > file.size){
      clearinterval(clock);
      return;
    }
    blob = file.slice(start,end);//根据长度截取每次需要上传的数据
    fd = new formdata();//每一次需要重新创建
    fd.append('video',blob);//添加数据到fd对象中
    up(fd);
    //重新设置开始和结尾
    start = end;
    end = start + length;
    sending = false;//上传完了
    //显示进度条
    percent = 100 * start/file.size;
    if(percent>100){
      percent = 100;
    }
    document.getelementbyid('bar').style.width = percent + '%';
    document.getelementbyid('bar').innerhtml = parseint(percent)+'%';
  });
})();
function up(fd){
  xhr.open('post','13-slice-upload.php',false);
  xhr.send(fd);
}
</script>
<style>
  #progress{
    width:500px;
    height:30px;
    border:1px solid green;
  }
  #bar{
    width:0%;
    height:100%;
    background-color: green;
  }
</style>
</head>
<body>
  <h1>大文件切割上传带进度条</h1>
  <div id="progress">
    <div id="bar"></div>
  </div>
  <input type="file" name="video" onchange="selfile();" />
</body>
</html>

13-slice-upload.php文件:

<?php
/**
 * 大文件切割上传,把每次上传的数据合并成一个文件
 * @author webbc
 */
$filename = './upload/upload.wmv';//确定上传的文件名
//第一次上传时没有文件,就创建文件,此后上传只需要把数据追加到此文件中
if(!file_exists($filename)){
  move_uploaded_file($_files['video']['tmp_name'],$filename);
}else{
  file_put_contents($filename,file_get_contents($_files['video']['tmp_name']),file_append);
}
?>

运行结果图: