<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Uploader
{
private $handler = null;
private $real_name = '';
private $allow_upload_types = array(); private $limit_size = 0;
public function __construct($data =array('imgtype'=>array(),'maxsize'=>null))
{
$this->allow_upload_types = $data['imgtype'];
if( $data['maxsize'] === null) $data['maxsize'] = $this->to_bytes(ini_get('upload_max_filesize'));
$this->limit_size = $data['maxsize'];
$ini_post_max_size = $this->to_bytes(ini_get('post_max_size'));
$ini_upload_max_filesize = $this->to_bytes(ini_get('upload_max_filesize'));
if ($ini_post_max_size < $this->limit_size || $ini_upload_max_filesize < $this->limit_size)
{
$require_size = max(1, $this->limit_size / 1024 / 1024) . 'M';
die("{'error':'请设置 php.ini 中 post_max_size 和 upload_max_filesize 值的最小为:$require_size'}");
}
if (strpos(strtolower($_SERVER['CONTENT_TYPE']), 'multipart/') === 0)
{
include 'uploader/Uploader_form.php';
$this->handler = new Uploader_form();
}
else
{
include 'uploader/Uploader_xhr.php';
$this->handler = new Uploader_xhr();
}
}
public function get_file_name()
{
return $this->handler->get_file_name();
}
public function get_file_size()
{
return $this->handler->get_file_size();
}
public function get_file_type()
{
if ($this->handler)
{
$file_name = strtolower($this->handler->get_file_name());
$pos = strrpos($file_name, '.');
if ($pos !== false)
{
return substr($file_name, $pos+1);
}
}
return '';
}
public function get_real_name()
{
return $this->real_name;
}
private function to_bytes($str){
$val = trim($str);
$last = strtolower($str[strlen($str)-1]);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
public function upload( $upload_dir )
{
if(!is_writable($upload_dir)) return array('error' => "没有写入权限.");
if(!$this->handler) return array('error' => '文件没有上传.');
$file_size = $this->handler->get_file_size();
if($file_size == 0) return array('error' => '文件不能为空');
if($file_size > $this->limit_size) return array('error' => '文件过大');
$file_type = $this->get_file_type();
if(count($this->allow_upload_types) && !in_array($file_type, $this->allow_upload_types))
{
$types = implode(', ', $this->allow_upload_types);
return array('error' => '禁止上传的格式,请上传以下格式 '. $types . '.');
}
$real_name = date('YmdHis').'-'.md5(uniqid()).'.'. $file_type;
$this->real_name = $real_name;
if( $this->handler->save($upload_dir.$real_name))
{
return array('success'=>true);
}
else
{
return array('error'=> '上传失败,服务器保存文件时出错!');
}
}
}