PHP实现原生态图片上传封装类方法
PHP图片上传类,经典方式,不过上传效率还算可以,我自己用过的一个类,当时对这个类做了些修改,以满足自己特定功能的需要,对PHP熟悉的,可对这个上传类做优化和修改,后附有调用方法,让PHP开发者上传图片轻松容易就做到,先上类代码: function TODO()
{//main 主类:设好参数,可以直接调用 $pass = true ; if ( ! $this -> GetFileAttri() ) { } if( ! $this -> CheckFileMIMEType() ) { $pass = false; $this -> error .= die("<script language="javascript">alert('图片类型不正确,允许格式:jpg|jpeg|gif|bmp。');history.back()"); } if( ! $this -> CheckFileAttri_size() ) { $this -> error .= die("<script language="javascript">alert('上传的文件太大,请确保在200K以内。');history.back()"); return false; } if ( ! $this -> MoveFileToNewPath() ) { return $pass; } function GetFileAttri() { foreach( $_FILES as $tmp ) { $this -> uploadFile = $tmp; } return (empty( $this -> uploadFile[ 'name' ])) ? false : true; } } } else { return false; } } function ChangeFileName ($prefix = NULL,$mode) {// string $prefix,int $mode $fullName = (isset($prefix)) ? $prefix."_" : NULL ; switch ($mode) { case 0 : $fullName .= rand( 0,100 ). "_" .strtolower(date ("ldSfFYhisa")) ; break; case 1 : $fullName .= rand( 0,100 ). "_" .time(); break; case 2 : $fullName .= rand( 0,10000 ) . time(); break; default : $fullName .= rand( 0,10000 ) . time(); break; } return $fullName; } function MoveFileToNewPath() { $newFileName = NULL; $newFileName = $this -> ChangeFileName( $this -> filePrefix,2 ). "." . $this -> GetFileTypeToString(); //检查目录是否存在,不存在则创建,当时我用的时候添加了这个功能,觉得没用的就注释掉吧 /* $isFile = file_exists( $this -> accessPath); clearstatcache(); if( ! $isFile && !is_dir($this -> accessPath) ) {
@mkdir($this -> accessPath); }*/ $array_dir=explode("/",$this -> accessPath);//把多级目录分别放到数组中 for($i=0;$i<count($array_dir);$i++){ $path .= $array_dir[$i]."/"; if(!file_exists($path)){ mkdir($path); } } ///////////////////////////////////////////////////////////////////////////////////////////////// if ( move_uploaded_file( $this -> uploadFile[ 'tmp_name' ],realpath( $this -> accessPath ) . "/" .$newFileName ) ) return $pass; } function GetFileTypeToString() { if( ! empty( $this -> uploadFile[ 'name' ] ) ) ?> 以下是PHP上传类的调用方法,PHP代码如下: $tmp = new FileUpload_Single;
$tmp -> accessPath ='upload';//图片上传的目录,这里是当前目录下的upload目录,可自己修改
if ( $tmp -> TODO() )
{
$filename=$tmp -> newFileName;//生成的文件名
echo "图片上传成功,路径为:upload/".$filename;
}else{
echo $tmp -> error;
}
} 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |