您好,欢迎访问一九零五行业门户网

thinkphp文件上传类

maxsize = $maxsize;
        }
        if(!empty($allowexts)) {
            if(is_array($allowexts)) {
                $this->allowexts = array_map('strtolower',$allowexts);
            }else {
                $this->allowexts = explode(',',strtolower($allowexts));
            }
        }
        if(!empty($allowtypes)) {
            if(is_array($allowtypes)) {
                $this->allowtypes = array_map('strtolower',$allowtypes);
            }else {
                $this->allowtypes = explode(',',strtolower($allowtypes));
            }
        }
        if(!empty($saverule)) {
            $this->saverule = $saverule;
        }else{
            $this->saverule=c('upload_file_rule');
        }
        $this->savepath = $savepath;
    }
    /**
     +----------------------------------------------------------
     * 上传一个文件
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param mixed $name 数据
     * @param string $value  数据表名
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws thinkexecption
     +----------------------------------------------------------
     */
    private function save($file) {
        $filename = $file['savepath'].$file['savename'];
        if(!$this->uploadreplace && is_file($filename)) {
            // 不覆盖同名文件
            $this->error='文件已经存在!'.$filename;
            return false;
        }
        // 如果是图像文件 检测文件格式
        if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file['tmp_name'])) {
            $this->error = '非法图像文件';
            return false;
        }
        if(!move_uploaded_file($file['tmp_name'], $this->auto_charset($filename,'utf-8','gbk'))) {
            $this->error = '文件上传保存错误!';
            return false;
        }
        if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
            $image =  getimagesize($filename);
            if(false !== $image) {
                //是图像文件生成缩略图
                $thumbwidth=explode(',',$this->thumbmaxwidth);
                $thumbheight=explode(',',$this->thumbmaxheight);
                $thumbprefix=explode(',',$this->thumbprefix);
                $thumbsuffix = explode(',',$this->thumbsuffix);
                $thumbfile=explode(',',$this->thumbfile);
                $thumbpath    =  $this->thumbpath?$this->thumbpath:$file['savepath'];
                // 生成图像缩略图
                import($this->imageclasspath);
                $realfilename  =  $this->autosub?basename($file['savename']):$file['savename'];
                for($i=0,$len=count($thumbwidth); $i                    $thumbname=$thumbpath.$thumbprefix[$i].substr($realfilename,0,strrpos($realfilename, '.')).$thumbsuffix[$i].'.'.$file['extension'];
                    image::thumb($filename,$thumbname,'',$thumbwidth[$i],$thumbheight[$i],true);
                }
                if($this->thumbremoveorigin) {
                    // 生成缩略图之后删除原图
                    unlink($filename);
                }
            }
        }
        if($this->zipimags) {
            // todo 对图片压缩包在线解压
        }
        return true;
    }
    /**
     +----------------------------------------------------------
     * 上传所有文件
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $savepath  上传文件保存路径
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws thinkexecption
     +----------------------------------------------------------
     */
    public function upload($savepath ='') {
        //如果不指定保存文件名,则由系统默认
        if(empty($savepath))
            $savepath = $this->savepath;
        // 检查上传目录
        if(!is_dir($savepath)) {
            // 检查目录是否编码后的
            if(is_dir(base64_decode($savepath))) {
                $savepath=base64_decode($savepath);
            }else{
                // 尝试创建目录
                if(!mkdir($savepath)){
                    $this->error  =  '上传目录'.$savepath.'不存在';
                    return false;
                }
            }
        }else {
            if(!is_writeable($savepath)) {
                $this->error  =  '上传目录'.$savepath.'不可写';
                return false;
            }
        }
        $fileinfo = array();
        $isupload   = false;
        // 获取上传的文件信息
        // 对$_files数组信息处理
        $files=$this->dealfiles($_files);
        foreach($files as $key => $file) {
            //过滤无效的上传
            if(!empty($file['name'])) {
                //登记上传文件的扩展信息
                $file['key']          =  $key;
                $file['extension']  = $this->getext($file['name']);
                $file['savepath']   = $savepath;
                $file['savename']   = $this->getsavename($file);
                // 自动检查附件
                if($this->autocheck) {
                    if(!$this->check($file))
                        return false;
                }
                //保存上传文件
                if(!$this->save($file)) return false;
                if(function_exists($this->hashtype)) {
                    $fun =  $this->hashtype;
                    $file['hash']   =  $fun($this->auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
                }
                //上传成功后保存文件信息,供其他地方调用
                unset($file['tmp_name'],$file['error']);
                $fileinfo[$key] = $file;
                $isupload   = true;
            }
        }
        if($isupload) {
            $this->uploadfileinfo = $fileinfo;
            return true;
        }else {
$this->error  =  '没有选择上传文件';
            return false;
        }
    }
    /**
     +----------------------------------------------------------
     * 上传单个上传字段中的文件 支持多附件
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param array $file  上传文件信息
     * @param string $savepath  上传文件保存路径
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws thinkexecption
     +----------------------------------------------------------
     */
    public function uploadone($file,$savepath=''){
        //如果不指定保存文件名,则由系统默认
        if(empty($savepath))
            $savepath = $this->savepath;
        // 检查上传目录
        if(!is_dir($savepath)) {
            // 尝试创建目录
            if(!mk_dir($savepath)){
                $this->error  =  '上传目录'.$savepath.'不存在';
                return false;
            }
        }else {
            if(!is_writeable($savepath)) {
                $this->error  =  '上传目录'.$savepath.'不可写';
                return false;
            }
        }
        //过滤无效的上传
        if(!empty($file['name'])) {
            $filearray = array();
            if(is_array($file['name'])) {
               $keys = array_keys($file);
               $count=count($file['name']);
               for ($i=0; $i                   foreach ($keys as $key)
                       $filearray[$i][$key] = $file[$key][$i];
               }
            }else{
                $filearray[] =  $file;
            }
            $info =  array();
            foreach ($filearray as $key=>$file){
                //登记上传文件的扩展信息
                $file['extension']  = $this->getext($file['name']);
                $file['savepath']   = $savepath;
                $file['savename']   = $this->getsavename($file);
                // 自动检查附件
                if($this->autocheck) {
                    if(!$this->check($file))
                        return false;
                }
                //保存上传文件
                if(!$this->save($file)) return false;
                if(function_exists($this->hashtype)) {
                    $fun =  $this->hashtype;
                    $file['hash']   =  $fun($this->auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
                }
                unset($file['tmp_name'],$file['error']);
                $info[] = $file;
            }
            // 返回上传的文件信息
            return $info;
        }else {
            $this->error  =  '没有选择上传文件';
            return false;
        }
    }
    // 自动转换字符集 支持数组转换
    private function auto_charset($fcontents, $from='gbk', $to='utf-8') {
        $from = strtoupper($from) == 'utf8' ? 'utf-8' : $from;
        $to = strtoupper($to) == 'utf8' ? 'utf-8' : $to;
        if (strtoupper($from) === strtoupper($to) || empty($fcontents) || (is_scalar($fcontents) && !is_string($fcontents))) {
            //如果编码相同或者非字符串标量则不转换
            return $fcontents;
        }
        if (is_string($fcontents)) {
            if (function_exists('mb_convert_encoding')) {
                return mb_convert_encoding($fcontents, $to, $from);
            } elseif (function_exists('iconv')) {
                return iconv($from, $to, $fcontents);
            } else {
                return $fcontents;
            }
        } elseif (is_array($fcontents)) {
            foreach ($fcontents as $key => $val) {
                $_key = $this->auto_charset($key, $from, $to);
                $fcontents[$_key] = $this->auto_charset($val, $from, $to);
                if ($key != $_key)
                    unset($fcontents[$key]);
            }
            return $fcontents;
        }
        else {
            return $fcontents;
        }
    }
/**
     +----------------------------------------------------------
     * 转换上传文件数组变量为正确的方式
     * 
     * 修改:
     *  当设置name=upload[]时,key为“upload”,对应一个包含多个文
     *  件信息的以数字索为引多维数组,name=upload1...,key为对应
     *  的名字
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param array $files  上传的文件变量
     +----------------------------------------------------------
     * @return array
     +----------------------------------------------------------
     */
    private function dealfiles($files) {
       $filearray = array();
       foreach ($files as $field => $file){
           if(is_array($file['name'])) {
               $keys = array_keys($file);
               $count=count($file['name']);
               for ($i=0; $i                   foreach ($keys as $key)
                       $filearray[$field][$key] = $file[$key][$i];
               }
           }else{
               $filearray[$field] = $file;
           }
       }
       return $filearray;
    }
    /**
     +----------------------------------------------------------
     * 获取错误代码信息
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $errorno  错误号码
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws thinkexecption
     +----------------------------------------------------------
     */
    protected function error($errorno) {
         switch($errorno) {
            case 1:
                $this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
                break;
            case 2:
                $this->error = '上传文件的大小超过了 html 表单中 max_file_size 选项指定的值';
                break;
            case 3:
                $this->error = '文件只有部分被上传';
                break;
            case 4:
                $this->error = '没有文件被上传';
                break;
            case 6:
                $this->error = '找不到临时文件夹';
                break;
            case 7:
                $this->error = '文件写入失败';
                break;
            default:
                $this->error = '未知上传错误!';
        }
        return ;
    }
    /**
     +----------------------------------------------------------
     * 根据上传文件命名规则取得保存文件名
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param string $filename 数据
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    private function getsavename($filename) {
        $rule = $this->saverule;
if(empty($rule)) {//没有定义命名规则,则保持文件名不变
            //$savename = $filename['name'];
$savename = date('ymdhis').rand()...$filename['extension'];
        }else{
if(function_exists($rule)) {
                //使用函数生成一个唯一文件标识号
                $savename = $rule()...$filename['extension'];
            }else {
                //使用给定的文件名作为标识号
                $savename = $rule...$filename['extension'];
            }
        }
        if($this->autosub) {
            // 使用子目录保存文件
            $filename['savename'] = $savename;
            $savename = $this->getsubname($filename).'/'.$savename;
        }
        return $savename;
    }
    /**
     +----------------------------------------------------------
     * 获取子目录的名称
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param array $file  上传的文件信息
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    private function getsubname($file) {
        switch($this->subtype) {
            case 'date':
                $dir   =  date($this->dateformat,time());
                break;
            case 'hash':
            default:
                $name = md5($file['savename']);
                $dir   =  '';
                for($i=0;$ihashlevel;$i++) {
                    $dir   .=  $name{$i}.'/';
                }
                break;
        }
        if(!is_dir($file['savepath'].$dir)) {
            mk_dir($file['savepath'].$dir);
        }
        return $dir;
    }
    /**
     +----------------------------------------------------------
     * 检查上传的文件
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param array $file 文件信息
     +----------------------------------------------------------
     * @return boolean
     +----------------------------------------------------------
     */
    private function check($file) {
        if($file['error']!== 0) {
            //文件上传失败
            //捕获错误代码
            $this->error($file['error']);
            return false;
        }
        //文件上传成功,进行自定义规则检查
        //检查文件大小
        if(!$this->checksize($file['size'])) {
            $this->error = '上传文件大小不符!';
            return false;
        }
        //检查文件mime类型
        if(!$this->checktype($file['type'])) {
            $this->error = '上传文件mime类型不允许!';
            return false;
        }
        //检查文件类型
        if(!$this->checkext($file['extension'])) {
            $this->error ='上传文件类型不允许';
            return false;
        }
        //检查是否合法上传
        if(!$this->checkupload($file['tmp_name'])) {
            $this->error = '非法上传文件!';
            return false;
        }
        return true;
    }
    /**
     +----------------------------------------------------------
     * 检查上传的文件类型是否合法
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param string $type 数据
     +----------------------------------------------------------
     * @return boolean
     +----------------------------------------------------------
     */
    private function checktype($type) {
        if(!empty($this->allowtypes))
            return in_array(strtolower($type),$this->allowtypes);
        return true;
    }
    /**
     +----------------------------------------------------------
     * 检查上传的文件后缀是否合法
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param string $ext 后缀名
     +----------------------------------------------------------
     * @return boolean
     +----------------------------------------------------------
     */
    private function checkext($ext) {
        if(!empty($this->allowexts))
            return in_array(strtolower($ext),$this->allowexts,true);
        return true;
    }
    /**
     +----------------------------------------------------------
     * 检查文件大小是否合法
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param integer $size 数据
     +----------------------------------------------------------
     * @return boolean
     +----------------------------------------------------------
     */
    private function checksize($size) {
        return !($size > $this->maxsize) || (-1 == $this->maxsize);
    }
    /**
     +----------------------------------------------------------
     * 检查文件是否非法提交
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param string $filename 文件名
     +----------------------------------------------------------
     * @return boolean
     +----------------------------------------------------------
     */
    private function checkupload($filename) {
        return is_uploaded_file($filename);
    }
    /**
     +----------------------------------------------------------
     * 取得上传文件的后缀
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param string $filename 文件名
     +----------------------------------------------------------
     * @return boolean
     +----------------------------------------------------------
     */
    private function getext($filename) {
        $pathinfo = pathinfo($filename);
        return $pathinfo['extension'];
    }
    /**
     +----------------------------------------------------------
     * 取得上传文件的信息
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return array
     +----------------------------------------------------------
     */
    public function getuploadfileinfo() {
        return $this->uploadfileinfo;
    }
    /**
     +----------------------------------------------------------
     * 取得最后一次错误信息
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    public function geterrormsg() {
        return $this->error;
    }
}
以上就介绍了thinkphp文件上传类,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息