Thinkphp拖拽上传文件-使用webuploader插件(自己改动了一些地方)——分片上传

html页面:  
  
  
  
  
Thinkphp拖拽上传文件-使用webuploader插件  
  
  
  
  
  
  

php:MafullController.class.php中写入上传方法:  
    /** 
     * webuploader 上传demo 
     */  
    public function webuploader(){  
        // 如果是post提交则显示上传的文件 否则显示上传页面  
        if(IS_POST){  
            $image=I('post.image');  
            // 判断是否有文件上传  
            if (empty($image)) {  
                die('没有上传文件');  
            }  
            echo '上传成功路径为:'.$image;  
        }else{  
            $this->display();  
        }  
    }  


//切片上传方法
	public function ajax_upload()
	{
		//故意写一个过期时间目的也是让浏览器去重新读取页面内容.你要知道,浏览器一般情况下去保存你访问过的页面的大部分内容,你第二次访问的时候,保存的内容(称为缓存)浏览器就不需要再向服务器请求了,这样节约时间,也减轻了服务器的负担.
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");//内容过期时间 
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");//标记内容最后修改时间
		header("Cache-Control: no-store, no-cache, must-revalidate");//强制不缓存
		header("Cache-Control: post-check=0, pre-check=0", false);//Internet Explorer 5对于HTTP头信息使用两种新的时间间隔指示
		header("Pragma: no-cache");//禁止本页被缓存

		//$_SERVER['REQUEST_METHOD']这个变量表示的是表单提交数据的方式,get或者post
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
			exit; // 完成预检CORS请求
		}
		if ( !empty($_REQUEST[ 'debug' ]) ) {
			$random = rand(0, intval($_REQUEST[ 'debug' ]) );
			if ( $random === 0 ) {
				header("HTTP/1.0 500 Internal Server Error");
				exit;
			}
		}

		// 5分钟执行时间
		@set_time_limit(5 * 60);
		$targetDir = 'Public\Upload'.DIRECTORY_SEPARATOR.'file_material_tmp';
		$uploadDir = 'Public\Upload'.DIRECTORY_SEPARATOR.'file_material';
		$cleanupTargetDir = true; // 是否删除以前的临时文件内容
		$maxFileAge = 5 * 3600; // 临时文件时间(以秒为单位)
		
		// 获取文件名
		if (!file_exists($targetDir)) {
			@mkdir($targetDir);//mkdir() 函数创建目录。
		}
		// 创建目标目录
		if (!file_exists($uploadDir)) {
			@mkdir($uploadDir);//mkdir() 函数创建目录。
		}
		
		// 获取文件名
		if (isset($_REQUEST["name"])) {
			$fileName = $_REQUEST["name"];
		} elseif (!empty($_FILES)) {
			$fileName = $_FILES["file"]["name"];
		} else {
			$fileName = uniqid("file_");
		}
		$fileName=iconv("UTF-8", "gb2312", $fileName);
		$oldName = $fileName;
		$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
		
		
		// 取得chunk和chunks
		$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
		$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
		
		
		// 删除以前的临时文件内容,如:file_material_tmp文件夹内的文件
		if ($cleanupTargetDir) {
			if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
			//is_dir -- 判断给定文件名是否是一个目录
			//opendir()函数的作用是:打开目录句柄。
				die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
			}
			while (($file = readdir($dir)) !== false) {//readdir ,readdir_r,----读一个目录
				$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
				// 如果临时文件是当前文件,继续下一步
				if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
					continue;
				}
				// 删除临时文件,如果它早于最大年龄,并且不是当前文件
				//preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 
				if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
					//filemtime() 函数返回文件内容上次的修改时间。若成功,则时间以 Unix 时间戳的方式返回。若失败,则返回 false。
					@unlink($tmpfilePath);//unlink() 函数删除文件。
				}
			}
			closedir($dir);
		}
		// 打开临时文件
		if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
			
			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
		}
		
		if (!empty($_FILES)) {
			if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
			}
			// 读取二进制输入流并将其附加到临时文件
			if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		} else {
			if (!$in = @fopen("php://input", "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		}
		while ($buff = fread($in, 4096)) {
			fwrite($out, $buff);
		}
		@fclose($out);
		@fclose($in);
		rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
		$index = 0;
		$done = true;
		for( $index = 0; $index < $chunks; $index++ ) {
			if ( !file_exists("{$filePath}_{$index}.part") ) {
				$done = false;
				break;
			}
		}

		if ( $done ) {
		$pathInfo = pathinfo($fileName);
		$hashStr = substr(md5($pathInfo['basename']),8,16);
		$hashName = time() . $hashStr . '.' .$pathInfo['extension'];
		$uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;

		if (!$out = @fopen($uploadPath, "wb")) {
			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
		}
		if ( flock($out, LOCK_EX) ) {
			for( $index = 0; $index < $chunks; $index++ ) {
				if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
					break;
				}
				while ($buff = fread($in, 4096)) {
					fwrite($out, $buff);
				}
				@fclose($in);
				@unlink("{$filePath}_{$index}.part");
			}
			flock($out, LOCK_UN);
		}
		@fclose($out);
		
		//$data=array();
		//$data['name']=$uploadPath;//Public\Upload\file_material\14793553561ee00a15b8a23204.jpg
		//echo json_encode($data);`
		
		//exit;
		//$data['name']=trim($uploadPath);
		$list = getimagesize($uploadPath);
		$data['pixels']=trim($list[0]."*".$list[1].'px');
		$response = array(
		        'success'=>true,
		        'oldName'=>$oldName,
		        'filePath'=>trim(str_replace("\\","/",substr($uploadPath,6))),
		        'fileSize'=>$data['size'],
		        'fileSuffixes'=>$pathInfo['extension'],
		        'file_id'=>$data['id'],
		        'filePixels'=>$data['pixels'],
	        );

		die(json_encode($response));
		}

		// 返回成功JSON-RPC响应
		die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');

	}

你可能感兴趣的:(【ThinkPHP3.2.3】)