PHP大文件分块上传功能实例详解

本文实例讲述了PHP大文件分块上传功能,分享给大家供大家参考,具体如下:

前端代码

使用file.slice将文件进行分割,然后分别进行异步上传。

  1. <!DOCTYPE html>
  2. <html >
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title><%= title %></title>
  8. <!-- zui -->
  9. <link rel="stylesheet" href="http://zui.sexy/dist/css/zui.min.css" rel="external nofollow" >
  10. </head>
  11. <body>
  12. <div class="container" >
  13. <form class="form-inline" method="post" enctype="multipart/form-data">
  14. <div class="form-group">
  15. <input type="file" class="form-control">
  16. </div>
  17. <button type="submit" class="btn btn-primary">提交</button>
  18. </form>
  19. </div>
  20. <!-- ZUI Javascript 依赖 jQuery -->
  21. <script src="http://zui.sexy/assets/jquery.js"></script>
  22. <!-- ZUI 标准版压缩后的 JavaScript 文件 -->
  23. <script src="http://zui.sexy/dist/js/zui.min.js"></script>
  24. <script type="text/javascript">
  25. $('form').submit(function() {
  26. let file = $(":file")[0].files[0];
  27. let fileName = file.name;
  28. let fileSize = file.size;
  29. console.log('fileSize',fileSize);
  30. let blockSize = 0.9*1024*1024;
  31. let num = Math.ceil(fileSize/blockSize);
  32. let start = 0;
  33. let end = 0;
  34. for(let i=1;i<=num;i++){
  35. end = blockSize*i;
  36. if(end > fileSize){
  37. end = fileSize;
  38. }
  39. let block = file.slice(start,end);
  40. start = end;
  41. let fd = new FormData();
  42. fd.append('block',block);
  43. fd.append('name',fileName);
  44. fd.append('total',num);
  45. fd.append('index',i);
  46. $.ajax({
  47. url:"upload.php",
  48. type:"POST",
  49. data:fd,
  50. async:true,
  51. processData:false,
  52. contentType:false,
  53. success:(res)=>{
  54. console.log('res_'+i+":");
  55. console.log(res);
  56. }
  57. })
  58. }
  59. return false;
  60. });
  61. </script>
  62. </body>
  63. </html>

后端代码

在所有的文件上传成功之后,合并生成原来的大文件

  1. <?php
  2. $name = $_POST['name'];
  3. $index = $_POST['index'];
  4. $total = $_POST['total'];
  5. echo "name:".$name.PHP_EOL;
  6. echo "index:".$index.PHP_EOL;
  7. echo "total:".$total.PHP_EOL;
  8. move_uploaded_file($_FILES['block']['tmp_name'],'upload/'.$name."_".$index);
  9. $list = scandir('upload');
  10. $num = count($list)-2;
  11. echo "cur_num:".$num.PHP_EOL;
  12. if($num == $total){
  13. echo "upload done".PHP_EOL;
  14. echo $cmd = "cat upload/'{$name}_'* > upload/'{$name}'";
  15. shell_exec($cmd);
  16. }