php结合web uploader插件实现分片上传文件

这篇文章主要为大家详细介绍了php结合web uploader插件实现分片上传文件, 采用大文件分片并发上传,极大的提高了文件上传效率,感兴趣的小伙伴们可以参考一下,最近研究了下大文件上传的方法,找到了webuploader js 插件进行大文件上传,大家也可以参考这篇文章进行学习:《Web Uploader文件上传插件使用详解》

使用

使用webuploader分成简单直选要引入

  1. <!--引入CSS-->
  2. <link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css">
  3. <!--引入JS-->
  4. <script type="text/javascript" src="webuploader文件夹/webuploader.js"></script>

HTML部分

  1. <div class="wu-example">
  2. <!--用来存放文件信息-->
  3. <div class="uploader-list"></div>
  4. <div class="btns">
  5. <div >选择文件</div>
  6. <button class="btn btn-default">开始上传 </button>
  7. </div>
  8. </div>

初始化Web Uploader

  1. jQuery(function() {
  2. $list = $('#thelist'),
  3. $btn = $('#ctlBtn'),
  4. state = 'pending',
  5. uploader;
  6. uploader = WebUploader.create({
  7. // 不压缩image
  8. resize: false,
  9. // swf文件路径
  10. swf: 'uploader.swf',
  11. // 文件接收服务端。
  12. server: upload.php,
  13. // 选择文件的按钮。可选。
  14. // 内部根据当前运行是创建,可能是input元素,也可能是flash.
  15. pick: '#picker',
  16. chunked: true,
  17. chunkSize:2*1024*1024,
  18. auto: true,
  19. accept: {
  20. title: 'Images',
  21. extensions: 'gif,jpg,jpeg,bmp,png',
  22. mimeTypes: 'image/*'
  23. }
  24. });

upload.php处理

以下是根据别人的例子自己拿来改的php 后台代码

  1. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  2. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  3. header("Cache-Control: no-store, no-cache, must-revalidate");
  4. header("Cache-Control: post-check=0, pre-check=0", false);
  5. header("Pragma: no-cache");
  6. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  7. exit; // finish preflight CORS requests here
  8. }
  9. if ( !emptyempty($_REQUEST[ 'debug' ]) ) {
  10. $random = rand(0, intval($_REQUEST[ 'debug' ]) );
  11. if ( $random === 0 ) {
  12. header("HTTP/1.0 500 Internal Server Error");
  13. exit;
  14. }
  15. }
  16. // header("HTTP/1.0 500 Internal Server Error");
  17. // exit;
  18. // 5 minutes execution time
  19. @set_time_limit(5 * 60);
  20. // Uncomment this one to fake upload time
  21. // usleep(5000);
  22. // Settings
  23. // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
  24. $targetDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material_tmp';
  25. $uploadDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material';
  26. $cleanupTargetDir = true; // Remove old files
  27. $maxFileAge = 5 * 3600; // Temp file age in seconds
  28. // Create target dir
  29. if (!file_exists($targetDir)) {
  30. @mkdir($targetDir);
  31. }
  32. // Create target dir
  33. if (!file_exists($uploadDir)) {
  34. @mkdir($uploadDir);
  35. }
  36. // Get a file name
  37. if (isset($_REQUEST["name"])) {
  38. $fileName = $_REQUEST["name"];
  39. } elseif (!emptyempty($_FILES)) {
  40. $fileName = $_FILES["file"]["name"];
  41. } else {
  42. $fileName = uniqid("file_");
  43. }
  44. $oldName = $fileName;
  45. $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
  46. // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
  47. // Chunking might be enabled
  48. $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
  49. $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
  50. // Remove old temp files
  51. if ($cleanupTargetDir) {
  52. if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
  53. die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
  54. }
  55. while (($file = readdir($dir)) !== false) {
  56. $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
  57. // If temp file is current file proceed to the next
  58. if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
  59. continue;
  60. }
  61. // Remove temp file if it is older than the max age and is not the current file
  62. if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
  63. @unlink($tmpfilePath);
  64. }
  65. }
  66. closedir($dir);
  67. }
  68. // Open temp file
  69. if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
  70. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  71. }
  72. if (!emptyempty($_FILES)) {
  73. if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
  74. die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  75. }
  76. // Read binary input stream and append it to temp file
  77. if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
  78. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  79. }
  80. } else {
  81. if (!$in = @fopen("php://input", "rb")) {
  82. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  83. }
  84. }
  85. while ($buff = fread($in, 4096)) {
  86. fwrite($out, $buff);
  87. }
  88. @fclose($out);
  89. @fclose($in);
  90. rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
  91. $index = 0;
  92. $done = true;
  93. for( $index = 0; $index < $chunks; $index++ ) {
  94. if ( !file_exists("{$filePath}_{$index}.part") ) {
  95. $done = false;
  96. break;
  97. }
  98. }
  99. if ( $done ) {
  100. $pathInfo = pathinfo($fileName);
  101. $hashStr = substr(md5($pathInfo['basename']),8,16);
  102. $hashName = time() . $hashStr . '.' .$pathInfo['extension'];
  103. $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;
  104. if (!$out = @fopen($uploadPath, "wb")) {
  105. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  106. }
  107. if ( flock($out, LOCK_EX) ) {
  108. for( $index = 0; $index < $chunks; $index++ ) {
  109. if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
  110. break;
  111. }
  112. while ($buff = fread($in, 4096)) {
  113. fwrite($out, $buff);
  114. }
  115. @fclose($in);
  116. @unlink("{$filePath}_{$index}.part");
  117. }
  118. flock($out, LOCK_UN);
  119. }
  120. @fclose($out);
  121. $response = [
  122. 'success'=>true,
  123. 'oldName'=>$oldName,
  124. 'filePaht'=>$uploadPath,
  125. 'fileSize'=>$data['size'],
  126. 'fileSuffixes'=>$pathInfo['extension'],
  127. 'file_id'=>$data['id'],
  128. ];
  129. die(json_encode($response));
  130. }
  131. // Return Success JSON-RPC response
  132. die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');