PHP大文件分割分片上传实现代码

这篇文章主要介绍了PHP大文件分割分片上传实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

upload_max_filesize = 2M //PHP最大能接受的文件大小

post_max_size = 8M //PHP能收到的最大POST值'

memory_limit = 128M //内存上限

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 >
  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. width: 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. #finish{
  19. background-color: #149bdf;
  20. 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);
  21. background-size:40px 40px;
  22. height: 100%;
  23. }
  24. form{
  25. margin-top: 50px;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <div >
  31. <div progress="0"></div>
  32. </div>
  33. <form action="./upload.php">
  34. <input type="file" name="file" >
  35. <input type="button" value="停止" >
  36. </form>
  37. <script>
  38. var fileForm = document.getElementById("file");
  39. var stopBtn = document.getElementById('stop');
  40. var upload = new Upload();
  41. fileForm.onchange = function(){
  42. upload.addFileAndSend(this);
  43. }
  44. stopBtn.onclick = function(){
  45. this.value = "停止中";
  46. upload.stop();
  47. this.value = "已停止";
  48. }
  49. function Upload(){
  50. var xhr = new XMLHttpRequest();
  51. var form_data = new FormData();
  52. const LENGTH = 1024 * 1024;
  53. var start = 0;
  54. var end = start + LENGTH;
  55. var blob;
  56. var blob_num = 1;
  57. var is_stop = 0
  58. //对外方法,传入文件对象
  59. this.addFileAndSend = function(that){
  60. var file = that.files[0];
  61. blob = cutFile(file);
  62. sendFile(blob,file);
  63. blob_num += 1;
  64. }
  65. //停止文件上传
  66. this.stop = function(){
  67. xhr.abort();
  68. is_stop = 1;
  69. }
  70. //切割文件
  71. function cutFile(file){
  72. var file_blob = file.slice(start,end);
  73. start = end;
  74. end = start + LENGTH;
  75. return file_blob;
  76. };
  77. //发送文件
  78. function sendFile(blob,file){
  79. var total_blob_num = Math.ceil(file.size / LENGTH);
  80. form_data.append('file',blob);
  81. form_data.append('blob_num',blob_num);
  82. form_data.append('total_blob_num',total_blob_num);
  83. form_data.append('file_name',file.name);
  84. xhr.open('POST','./upload.php',false);
  85. xhr.onreadystatechange = function () {
  86. var progress;
  87. var progressObj = document.getElementById('finish');
  88. if(total_blob_num == 1){
  89. progress = '100%';
  90. }else{
  91. progress = Math.min(100,(blob_num/total_blob_num)* 100 ) +'%';
  92. }
  93. progressObj.style.width = progress;
  94. var t = setTimeout(function(){
  95. if(start < file.size && is_stop === 0){
  96. blob = cutFile(file);
  97. sendFile(blob,file);
  98. blob_num += 1;
  99. }else{
  100. setTimeout(t);
  101. }
  102. },1000);
  103. }
  104. xhr.send(form_data);
  105. }
  106. }
  107. </script>
  108. </body>
  109. </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. public function __construct($tmpPath,$blobNum,$totalBlobNum,$fileName){
  9. $this->tmpPath = $tmpPath;
  10. $this->blobNum = $blobNum;
  11. $this->totalBlobNum = $totalBlobNum;
  12. $this->fileName = $fileName;
  13. $this->moveFile();
  14. $this->fileMerge();
  15. }
  16. //判断是否是最后一块,如果是则进行文件合成并且删除文件块
  17. private function fileMerge(){
  18. if($this->blobNum == $this->totalBlobNum){
  19. $blob = '';
  20. for($i=1; $i<= $this->totalBlobNum; $i++){
  21. $blob .= file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i);
  22. }
  23. file_put_contents($this->filepath.'/'. $this->fileName,$blob);
  24. $this->deleteFileBlob();
  25. }
  26. }
  27. //删除文件块
  28. private function deleteFileBlob(){
  29. for($i=1; $i<= $this->totalBlobNum; $i++){
  30. @unlink($this->filepath.'/'. $this->fileName.'__'.$i);
  31. }
  32. }
  33. //移动文件
  34. private function moveFile(){
  35. $this->touchDir();
  36. $filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;
  37. move_uploaded_file($this->tmpPath,$filename);
  38. }
  39. //API返回数据
  40. public function apiReturn(){
  41. if($this->blobNum == $this->totalBlobNum){
  42. if(file_exists($this->filepath.'/'. $this->fileName)){
  43. $data['code'] = 2;
  44. $data['msg'] = 'success';
  45. $data['file_path'] = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['DOCUMENT_URI']).str_replace('.','',$this->filepath).'/'. $this->fileName;
  46. }
  47. }else{
  48. if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){
  49. $data['code'] = 1;
  50. $data['msg'] = 'waiting for all';
  51. $data['file_path'] = '';
  52. }
  53. }
  54. header('Content-type: application/json');
  55. echo json_encode($data);
  56. }
  57. //建立上传文件夹
  58. private function touchDir(){
  59. if(!file_exists($this->filepath)){
  60. return mkdir($this->filepath);
  61. }
  62. }
  63. }
  64. //实例化并获取系统变量传参
  65. $upload = new Upload($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']);
  66. //调用方法,返回结果
  67. $upload->apiReturn();