PHP搭建大文件切割分块上传功能示例

背景

在网站开发中,文件上传是很常见的一个功能。相信很多人都会遇到这种情况,想传一个文件上去,然后网页提示“该文件过大”。因为一般情况下,我们都需要对上传的文件大小做限制,防止出现意外的情况。
 但是在有些业务场景中,大文件上传又是必须的,比如邮箱附件,或者内部OA等等。

问题

服务端为什么不能直接传大文件?跟php.ini里面的几个配置有关

1 upload_max_filesize = 2M //PHP最大能接受的文件大小
2 post_max_size = 8M //PHP能收到的最大POST值'
3 memory_limit = 128M //内存上限
4 max_execution_time = 30 //最大执行时间

当然不能简单粗暴的把上面几个值调大,否则服务器内存资源吃光是迟早的问题。

解决思路

好在HTML5开放了新的FILE API,也可以直接操作二进制对象,我们可以直接在浏览器端实现文件切割,按照以前的做法就得用Flash的方案,实现起来会麻烦很多。

JS思路

1.监听上传按钮的onchange事件

2.获取文件的FILE对象

3.把文件的FILE对象进行切割,并且附加到FORMDATA对象中

4.把FORMDATA对象通过AJAX发送到服务器

5.重复3、4步骤,直到文件发送完。

PHP思路

1.建立上传文件夹

2.把文件从上传临时目录移动到上传文件夹

3.所有的文件块上传完成后,进行文件合成

4.删除文件夹

5.返回上传后的文件路径

DEMO代码

前端部分代码

  1 <!doctype html>
  2 <html lang="en">
  3 <head>
  4  <meta charset="UTF-8">
  5  <meta name="viewport"
  6    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  7  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8  <title>Document</title>
  9  <style>
 10   #progress{
 11     300px;
 12    height: 20px;
 13    background-color:#f7f7f7;
 14    box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);
 15    border-radius:4px;
 16    background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);
 17   }
 18  
 19   #finish{
 20    background-color: #149bdf;
 21    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);
 22    background-size:40px 40px;
 23    height: 100%;
 24   }
 25   form{
 26    margin-top: 50px;
 27   }
 28  </style>
 29 </head>
 30 <body>
 31 <div id="progress">
 32  <div id="finish" style=" 0%;" progress="0"></div>
 33 </div>
 34 <form action="./upload.php">
 35  <input type="file" name="file" id="file">
 36  <input type="button" value="停止" id="stop">
 37 </form>
 38 <script>
 39  var fileForm = document.getElementById("file");
 40  var stopBtn = document.getElementById('stop');
 41  var upload = new Upload();
 42  
 43  fileForm.onchange = function(){
 44   upload.addFileAndSend(this);
 45  }
 46  
 47  stopBtn.onclick = function(){
 48   this.value = "停止中";
 49   upload.stop();
 50   this.value = "已停止";
 51  }
 52  
 53  function Upload(){
 54   var xhr = new XMLHttpRequest();
 55   var form_data = new FormData();
 56   const LENGTH = 1024 * 1024;
 57   var start = 0;
 58   var end = start + LENGTH;
 59   var blob;
 60   var blob_num = 1;
 61   var is_stop = 0
 62   //对外方法,传入文件对象
 63   this.addFileAndSend = function(that){
 64    var file = that.files[0];
 65    blob = cutFile(file);
 66    sendFile(blob,file);
 67    blob_num += 1;
 68   }
 69   //停止文件上传
 70   this.stop = function(){
 71    xhr.abort();
 72    is_stop = 1;
 73   }
 74   //切割文件
 75   function cutFile(file){
 76    var file_blob = file.slice(start,end);
 77    start = end;
 78    end = start + LENGTH;
 79    return file_blob;
 80   };
 81   //发送文件
 82   function sendFile(blob,file){
 83    var total_blob_num = Math.ceil(file.size / LENGTH);
 84    form_data.append('file',blob);
 85    form_data.append('blob_num',blob_num);
 86    form_data.append('total_blob_num',total_blob_num);
 87    form_data.append('file_name',file.name);
 88  
 89    xhr.open('POST','./upload.php',false);
 90    xhr.onreadystatechange = function () {
 91     var progress;
 92     var progressObj = document.getElementById('finish');
 93     if(total_blob_num == 1){
 94      progress = '100%';
 95     }else{
 96      progress = Math.min(100,(blob_num/total_blob_num)* 100 ) +'%';
 97     }
 98     progressObj.style.width = progress;
 99     var t = setTimeout(function(){
100      if(start < file.size && is_stop === 0){
101       blob = cutFile(file);
102       sendFile(blob,file);
103       blob_num += 1;
104      }else{
105       setTimeout(t);
106      }
107     },1000);
108    }
109    xhr.send(form_data);
110   }
111  }
112  
113 </script>
114 </body>
115 </html>

PHP部分代码

 1 <?php
 2 class Upload{
 3  private $filepath = './upload'; //上传目录
 4  private $tmpPath; //PHP文件临时目录
 5  private $blobNum; //第几个文件块
 6  private $totalBlobNum; //文件块总数
 7  private $fileName; //文件名
 8  
 9  public function __construct($tmpPath,$blobNum,$totalBlobNum,$fileName){
10   $this->tmpPath = $tmpPath;
11   $this->blobNum = $blobNum;
12   $this->totalBlobNum = $totalBlobNum;
13   $this->fileName = $fileName;
14    
15   $this->moveFile();
16   $this->fileMerge();
17  }
18   
19  //判断是否是最后一块,如果是则进行文件合成并且删除文件块
20  private function fileMerge(){
21   if($this->blobNum == $this->totalBlobNum){
22    $blob = '';
23    for($i=1; $i<= $this->totalBlobNum; $i++){
24     $blob .= file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i);
25    }
26    file_put_contents($this->filepath.'/'. $this->fileName,$blob);
27    $this->deleteFileBlob();
28   }
29  }
30   
31  //删除文件块
32  private function deleteFileBlob(){
33   for($i=1; $i<= $this->totalBlobNum; $i++){
34    @unlink($this->filepath.'/'. $this->fileName.'__'.$i);
35   }
36  }
37   
38  //移动文件
39  private function moveFile(){
40   $this->touchDir();
41   $filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;
42   move_uploaded_file($this->tmpPath,$filename);
43  }
44   
45  //API返回数据
46  public function apiReturn(){
47   if($this->blobNum == $this->totalBlobNum){
48     if(file_exists($this->filepath.'/'. $this->fileName)){
49      $data['code'] = 2;
50      $data['msg'] = 'success';
51      $data['file_path'] = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['DOCUMENT_URI']).str_replace('.','',$this->filepath).'/'. $this->fileName;
52     }
53   }else{
54     if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){
55      $data['code'] = 1;
56      $data['msg'] = 'waiting for all';
57      $data['file_path'] = '';
58     }
59   }
60   header('Content-type: application/json');
61   echo json_encode($data);
62  }
63   
64  //建立上传文件夹
65  private function touchDir(){
66   if(!file_exists($this->filepath)){
67    return mkdir($this->filepath);
68   }
69  }
70 }
71  
72 //实例化并获取系统变量传参
73 $upload = new Upload($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']);
74 //调用方法,返回结果
75 $upload->apiReturn();

存在的问题

这只是一个简单的DEMO,有很多地方需要改进,比如上传的文件夹与临时文件放在一起,用户中途取消也没有发请求进行清理,容易造成文件冗余。JS采用的是同步模型,文件需要一块一块按顺序上传,会导致整个浏览器在上传的过程中出于堵塞的状态,按了按钮可能需要几秒钟才能反应过来,用户体验不好。真正需要产品化的时候就要综合考虑多种情况,当然作为一个示例,引导大家了解分块上传的思路还是不错的。

原文链接:http://www.cnblogs.com/jaychan/p/6245026.html

原文地址:https://www.cnblogs.com/jdwang-admin/p/7290604.html