ThinkPHP5 使用webuploader 大文件分片上传合并
webuploader 参考网址:
http://fex.baidu.com/webuploader/
首先引入Jquery 引入webuploader插件 及js css
1 <!--引入CSS--> 2 <link rel="stylesheet" type="text/css" href="/webuploader/webuploader.css">
3 <!--引入Jquery--> 4 <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
5 <!--引入JS--> 6 <script type="text/javascript" src="/webuploader/webuploader.js"></script>
HTML:
1 <div class="demo"> 2 <div id="uploadfile"> 3 <!--用来存放文件信息--> 4 <div id="the_2655" class="uploader-list"></div> 5 <div class="form-group form-inline"> 6 <div id="picker" style="float:left">选择文件</div> 7 <input type="hidden" value="" id="file" name="file"> 8 <button id="Btn_2655" class="btn btn-default" style="padding: 5px 10px;border-radius: 3px;">开始上传</button> 9 </div> 10 </div> 11 </div>
Script:
1 $(function () { 2 var uploader = WebUploader.create({ 3 // swf文件路径 4 swf: 'webuploader/Uploader.swf', 5 // 文件接收服务端。 6 server: "{:url('index/uploadFile')}", 7 // 选择文件的按钮 8 pick: "#picker", 9 // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传! 10 resize: false, 11 // 选完文件后,是否自动上传。 12 auto:true, 13 // 图片name 14 fileVal:'file', 15 // 单文件 16 multiple:false, 17 //是否要分片处理大文件上传 18 chunked: true, 19 //分片上传,每片2M,默认是5M 20 chunkSize:5*1024*1024, 21 // 单个文件大小限制 5 G 22 fileSingleSizeLimit: 10*1024* 1024 * 1024, 23 compress : { 24 width: 100, 25 height: 100, 26 compressSize: 0 27 }, 28 }); 29 uploader.on( 'uploadSuccess', function( file,res ) { 30 $('#file').val(res.filePath) 31 }); 32 })
PHP:
1 public function uploadFile(){ 2 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 3 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 4 header("Content-type: text/html; charset=gbk32"); 5 header("Cache-Control: no-store, no-cache, must-revalidate"); 6 header("Cache-Control: post-check=0, pre-check=0", false); 7 header("Pragma: no-cache"); 8 $folder = input('folder'); 9 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { 10 exit; // finish preflight CORS requests here 11 } 12 if ( !empty($_REQUEST[ 'debug' ]) ) { 13 $random = rand(0, intval($_REQUEST[ 'debug' ]) ); 14 if ( $random === 0 ) { 15 header("HTTP/1.0 500 Internal Server Error"); 16 exit; 17 } 18 } 19 // header("HTTP/1.0 500 Internal Server Error"); 20 // exit; 21 // 5 minutes execution time 22 set_time_limit(5 * 60); 23 // Uncomment this one to fake upload time 24 usleep(5000); 25 // Settings 26 $targetDir = './Public'.DIRECTORY_SEPARATOR.'file_material_tmp'; //存放分片临时目录 27 if($folder){ 28 $uploadDir = './Public'.DIRECTORY_SEPARATOR.'file_material'.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.date('Ymd'); 29 }else{ 30 $uploadDir = './Public'.DIRECTORY_SEPARATOR.'file_material'.DIRECTORY_SEPARATOR.date('Ymd'); //分片合并存放目录 31 } 32 33 $cleanupTargetDir = true; // Remove old files 34 $maxFileAge = 5 * 3600; // Temp file age in seconds 35 36 // Create target dir 37 if (!file_exists($targetDir)) { 38 mkdir($targetDir,0777,true); 39 } 40 // Create target dir 41 if (!file_exists($uploadDir)) { 42 mkdir($uploadDir,0777,true); 43 } 44 // Get a file name 45 if (isset($_REQUEST["name"])) { 46 $fileName = $_REQUEST["name"]; 47 } elseif (!empty($_FILES)) { 48 $fileName = $_FILES["file"]["name"]; 49 } else { 50 $fileName = uniqid("file_"); 51 } 52 $oldName = $fileName; 53 54 $fileName = iconv('UTF-8','gb2312',$fileName); 55 $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; 56 // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName; 57 // Chunking might be enabled 58 $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; 59 $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1; 60 // Remove old temp files 61 if ($cleanupTargetDir) { 62 if (!is_dir($targetDir) || !$dir = opendir($targetDir)) { 63 die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory111."}, "id" : "id"}'); 64 } 65 while (($file = readdir($dir)) !== false) { 66 $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; 67 // If temp file is current file proceed to the next 68 if ($tmpfilePath == "{$filePath}_{$chunk}" || $tmpfilePath == "{$filePath}_{$chunk}") { 69 continue; 70 } 71 // Remove temp file if it is older than the max age and is not the current file 72 if (preg_match('/\.(part|parttmp)$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) { 73 unlink($tmpfilePath); 74 } 75 } 76 closedir($dir); 77 } 78 // Open temp file 79 if (!$out = fopen("{$filePath}_{$chunk}", "wb")) { 80 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream222."}, "id" : "id"}'); 81 } 82 if (!empty($_FILES)) { 83 if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { 84 die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file333."}, "id" : "id"}'); 85 } 86 // Read binary input stream and append it to temp file 87 if (!$in = fopen($_FILES["file"]["tmp_name"], "rb")) { 88 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream444."}, "id" : "id"}'); 89 } 90 } else { 91 if (!$in = fopen("php://input", "rb")) { 92 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream555."}, "id" : "id"}'); 93 } 94 } 95 while ($buff = fread($in, 4096)) { 96 fwrite($out, $buff); 97 } 98 fclose($out); 99 fclose($in); 100 rename("{$filePath}_{$chunk}", "{$filePath}_{$chunk}"); 101 $index = 0; 102 $done = true; 103 for( $index = 0; $index < $chunks; $index++ ) { 104 if ( !file_exists("{$filePath}_{$index}") ) { 105 $done = false; 106 break; 107 } 108 } 109 110 if ($done) { 111 $pathInfo = pathinfo($fileName); 112 $hashStr = substr(md5($pathInfo['basename']),8,16); 113 $hashName = time() . $hashStr . '.' .$pathInfo['extension']; 114 $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName; 115 if (!$out = fopen($uploadPath, "wb")) { 116 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream666."}, "id" : "id"}'); 117 } 118 //flock($hander,LOCK_EX)文件锁 119 if ( flock($out, LOCK_EX) ) { 120 for( $index = 0; $index < $chunks; $index++ ) { 121 if (!$in = fopen("{$filePath}_{$index}", "rb")) { 122 break; 123 } 124 while ($buff = fread($in, 4096)) { 125 fwrite($out, $buff); 126 } 127 fclose($in); 128 unlink("{$filePath}_{$index}"); 129 } 130 flock($out, LOCK_UN); 131 } 132 fclose($out); 133 $response = [ 134 'success'=>true, 135 'oldName'=>$oldName, 136 'filePath'=>$uploadPath, 137 // 'fileSize'=>$data['size'], 138 'fileSuffixes'=>$pathInfo['extension'], //文件后缀名 139 // 'file_id'=>$data['id'], 140 ]; 141 return json($response); 142 } 143 144 // Return Success JSON-RPC response 145 die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); 146 }