LtUpload上傳組件

來源:互聯網
上載者:User

標籤:des   http   io   color   ar   os   for   sp   檔案   

<?php
/**
* The Upload class
* @author Alex Lee <[email protected]>
* @license http://opensource.org/licenses/BSD-3-Clause New BSD License
* @version svn:$Id: Upload.php 2014-11-2 22:12:32Z [email protected] $
*/

/**
* @category runtime
* @package Lotusphp\Upload
*/

error_reporting(0); //屏蔽所有錯誤資訊

class LtUpload
{
/** @var LtConfig config handle */
public $configHandle;

/** @var array config */
public $conf;
public $confgroup;
//getimagesize + $_FILES值
public $getData = ‘‘;
private $dir_sep = DIRECTORY_SEPARATOR;
private $err = array(‘fileEmpty‘=>‘上傳的檔案為空白‘,‘fileIllegal‘=>‘上傳檔案非法‘,‘filePostfixIllegal‘=>‘上傳檔案格式非法‘,‘fileSizeIllegal‘=>‘上傳檔案大小非法‘,‘fileFailure‘=>‘上傳檔案失敗‘,‘fileSizeToosmall‘=>‘圖片像素太小‘,‘fileLayer‘=>‘分割檔案名稱寬度超出範圍‘,‘fileCreateDir‘=>‘建立目錄沒有許可權‘);

/**
* construct
*/
public function __construct()
{
if (! $this->configHandle instanceof LtConfig)
{
if (class_exists("LtObjectUtil", false))
{
$this->configHandle = LtObjectUtil::singleton("LtConfig");
}
else
{
$this->configHandle = new LtConfig;
}
}
}

/**
* init
*/
public function init()
{
$this->confgroup = $this->configHandle->get("upload");
if (empty($this->confgroup[‘default‘]))
{
//詳細配置資訊(預設配置)
//預設只允許上傳gif、jpeg、png、bmp
$this->confgroup[‘default‘][‘fileType‘] = ‘image‘; //類型為圖片,參數為file則為只上傳
$this->confgroup[‘default‘][‘cutting‘] = FALSE; //是否需要切圖
$this->confgroup[‘default‘][‘cutType‘] = 1; //切圖方式,1:等比縮放,2:
$this->confgroup[‘default‘][‘cutSize‘] = array(array(‘width‘=>0,‘height‘=>0)); //預設等比例縮微切割寬度
$this->confgroup[‘default‘][‘allowType‘] = array(‘gif‘,‘jpeg‘,‘jpg‘,‘png‘); //可以上傳的圖片類型
$this->confgroup[‘default‘][‘checkType‘] = TRUE; //是否檢查圖片格式
$this->confgroup[‘default‘][‘checkSize‘] = TRUE; //是否檢查圖片大小
$this->confgroup[‘default‘][‘maxSize‘] = 2097152; //上傳最大值, 單位位元組
$this->confgroup[‘default‘][‘pathFormat‘] =‘/upload/image/{yyyy}{mm}/{dd}/{time}{rand:6}‘;

$this->conf = $this->confgroup[‘default‘];
}
else
{
$this->conf = $this->confgroup[‘default‘];
}
}

public function setUpload($configName)
{
$this->confgroup[$configName]? $this->conf = $this->confgroup[$configName] : $this->conf = $this->confgroup[‘default‘];
}

//檔案原圖上傳
public function put($arr_files = array()) {
$this->getData = & $arr_files;

//判斷是否為空白
if(!isset($this->getData[‘tmp_name‘]) || !isset($this->getData[‘name‘]) || empty($this->getData[‘tmp_name‘]) || empty($this->getData[‘name‘])) {
$this->halt($this->err[‘fileEmpty‘]);
}

//判斷是否上傳失敗
if(isset($this->getData[‘error‘]) && $this->getData[‘error‘]) {
$this->halt($this->err[‘fileFailure‘]);
}

if(is_uploaded_file($this->getData[‘tmp_name‘])) {
$this->checkSafe();
$this->createNewPath();
$this->createDir();

//圖片或者檔案都可以上傳
return $this->doUpload() ? $this->getData : $this->err[‘fileFailure‘];
}
}

/**
* 檔案上傳開始
*
* @param <string> tmp_name
* @param <string> path, new_path
* @return <boolean>
*/
private function doUpload() {
if(move_uploaded_file($this->getData[‘tmp_name‘], $_SERVER[‘DOCUMENT_ROOT‘].DIRECTORY_SEPARATOR.$this->getData[‘full_path‘])) {
return TRUE;
}
return FALSE;
}

/**
* 判斷上傳檔案大小是否合法
*
* @param <number> size檔案大小值
* @return <boolean>
*/
private function checkSize() {
if($this->conf[‘checkSize‘] && $this->getData[‘size‘] > $this->conf[‘maxSize‘]) {
return FALSE;
}
return TRUE;
}

/**
* 取得檔案名稱尾碼
*
* @param <string> name
* @return <string>返回尾碼名稱
*/
private function getPostfix() {
return strtolower(trim(substr(strrchr($this->getData[‘name‘], ‘.‘), 1, 10)));
}

/**
* 檢查檔案是否為規定上傳類型
*
* @param <string> name
* @return <boolean>
*/
private function checkFormat() {
if($this->conf[‘checkType‘] && !in_array($this->getPostfix(), $this->conf[‘allowType‘])) {
return FALSE;
}
return TRUE;
}

/**
* 建立分隔目錄
*
* @param <string> path配置目錄, new_path完整目錄
*/
private function createDir() {
$realpath=$_SERVER[‘DOCUMENT_ROOT‘].DIRECTORY_SEPARATOR.$this->getData[‘full_path‘];
if(!file_exists($path = dirname($realpath))) {
if([email protected]($path, 0777, TRUE)) {
return $this->err[‘fileCreateDir‘];
}
}
}

/**
* $autoDir 如果為假, 目錄分割功能關閉
*
* @param <string> new_name, new_dir, new_path
* @return <string> new_dir, new_path
*/
private function createNewPath() {

$t = time();
$d = explode(‘-‘, date("Y-y-m-d-H-i-s"));
$format = $this->conf["pathFormat"];
$format = str_replace("{yyyy}", $d[0], $format);
$format = str_replace("{yy}", $d[1], $format);
$format = str_replace("{mm}", $d[2], $format);
$format = str_replace("{dd}", $d[3], $format);
$format = str_replace("{hh}", $d[4], $format);
$format = str_replace("{ii}", $d[5], $format);
$format = str_replace("{ss}", $d[6], $format);
$format = str_replace("{time}", $t, $format);

//替換隨機字串
$randNum = rand(1, 10000000000) . rand(1, 10000000000);
if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
$format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
}
$this->getData[‘full_path‘]= $format.‘.‘.$this->getPostfix();
}

/**
* 圖片有效性檢測
*
* @param <string> fullPath 完整全路徑地址
* @return <string> width圖片寬度, height圖片高度, img_type_number圖片數字類型
*/
private function checkSafe() {
if(!$this->checkFormat()) {
$this->halt($this->err[‘filePostfixIllegal‘]);
}

if(!$this->checkSize()) {
$this->halt($this->err[‘fileSizeIllegal‘]);
}

$this->getImage();
}

/**
* 取得圖片的長、寬、類型
*
* @param <string> fullPath 完整全路徑地址
*/
private function getImage($fullPath = ‘‘) {
if ($this->conf[‘fileType‘] == ‘image‘) {
list($this->getData[‘width‘], $this->getData[‘height‘], $this->getData[‘img_type_number‘]) = getimagesize($fullPath ? $fullPath : $this->getData[‘tmp_name‘]);
if(!in_array($this->getData[‘img_type_number‘], array(1,2,3))) {
$this->halt($this->err[‘filePostfixIllegal‘]);
}
}
}

/**
* 產生等比例縮微圖thumb
*
* @return <boolean> TRUE 成功, FALSE 失敗
*/
public function putThumb() {
$filePath = $_SERVER[‘DOCUMENT_ROOT‘].DIRECTORY_SEPARATOR.$this->getData[‘full_path‘];

if($filePath && $this->conf[‘fileType‘] == ‘image‘ && $this->conf[‘cutting‘] && @file_exists($filePath)) {

if(!isset($this->getData[‘width‘]) || !isset($this->getData[‘height‘])) {
$this->getImage($filePath);
}

if(!in_array($this->getData[‘img_type_number‘], array(1,2,3))) {
return $this->err[‘filePostfixIllegal‘];
}

switch($this->getData[‘img_type_number‘]) {
case 1:
$im = imagecreatefromgif($filePath);
break;
case 2:
$im = imagecreatefromjpeg($filePath);
break;
case 3:
$im = imagecreatefrompng($filePath);
break;
}

if(!$im) {
return FALSE;
}


foreach($this->conf[‘cutSize‘] as $img){
$imgWidth=$img[‘width‘];
$imgHeight=$img[‘height‘];
$filename=$img[‘width‘].‘-‘.$img[‘height‘];

if($img[‘width‘] > $this->getData[‘width‘] && $img[‘width‘]>0){$img[‘width‘] = $this->getData[‘width‘];}
if($img[‘height‘] > $this->getData[‘height‘] && $img[‘height‘]>0){ $img[‘height‘]= $this->getData[‘height‘];}

$width = $img[‘width‘];
$height = $img[‘height‘];


if ($img[‘width‘]>0 && ($this->getData[‘width‘] < $this->getData[‘height‘])) {
$width = ($img[‘height‘] / $this->getData[‘height‘]) * $this->getData[‘width‘];
} else {
$height = ($img[‘width‘] / $this->getData[‘width‘]) * $this->getData[‘height‘];
}

if (function_exists("imagecreatetruecolor")) {

if($this->conf[‘cutType‘] ==1 ){
$new = imagecreatetruecolor($width, $height);

$this->getData[‘img_type_number‘] == 3 && $this->transparent($new);
imagecopyresampled($new, $im, 0, 0, 0, 0, $width, $height, $this->getData[‘width‘], $this->getData[‘height‘]);
}else{
$dst_x = 0;
$dst_y = 0;
if ( ($imgWidth/$imgHeight - $width/$height) > 0 ) {
$dst_x = ( $imgWidth - $width ) / 2;
} elseif ( ($imgWidth/$imgHeight - $width/$height) < 0 ) {
$dst_y = ( $imgHeight - $height ) / 2;
}

$new = imagecreatetruecolor($imgWidth, $imgHeight);
$color = imagecolorallocate($new, hexdec(substr($this->conf[‘bgcolor‘], 1, 2)), hexdec(substr($this->conf[‘bgcolor‘], 3, 2)), hexdec(substr($this->conf[‘bgcolor‘], 5, 2)));
imagefill($new, 0, 0, $color);
imagecopyresampled($new, $im, $dst_x, $dst_y, 0, 0, $width, $height, $this->getData[‘width‘], $this->getData[‘height‘]);
}


} else {
$new = imagecreate($width, $height);
if($this->conf[‘cutType‘] ==1 ){
$new = imagecreatetruecolor($width, $height);
$this->getData[‘img_type_number‘] == 3 && $this->transparent($new);
imagecopyresampled($new, $im, 0, 0, 0, 0, $width, $height, $this->getData[‘width‘], $this->getData[‘height‘]);
}else{
$dst_x = 0;
$dst_y = 0;
if ( ($imgWidth/$imgHeight - $width/$height) > 0 ) {
$dst_x = ( $imgWidth - $width ) / 2;
} elseif ( ($imgWidth/$imgHeight - $width/$height) < 0 ) {
$dst_y = ( $imgHeight - $height ) / 2;
}
$new = imagecreatetruecolor($imgWidth, $imgHeight);
$color = imagecolorallocate($new, hexdec(substr($this->conf[‘bgcolor‘], 1, 2)), hexdec(substr($this->conf[‘bgcolor‘], 3, 2)), hexdec(substr($this->conf[‘bgcolor‘], 5, 2)));
imagefill($new, 0, 0, $color);
imagecopyresampled($new, $im, $dst_x, $dst_y, 0, 0, $width, $height, $this->getData[‘width‘], $this->getData[‘height‘]);
}
}

$newFilePath = $_SERVER[‘DOCUMENT_ROOT‘].DIRECTORY_SEPARATOR.$this->getData[‘full_path‘]. ‘.‘ . $filename;

switch ($this->getData[‘img_type_number‘]) {
case 1:
imagegif($new, $newFilePath. ‘.gif‘);
break;
case 2:
imagejpeg($new, $newFilePath. ‘.jpg‘, 100);
break;
case 3:
imagepng($new, $newFilePath. ‘.png‘);
break;
}
unset($filePath,$filename, $newFilePath, $width, $height);

}
imagedestroy($new); imagedestroy($im);
return TRUE;
}

return FALSE;
}

/**
* PNG透明背景圖片處理
*
* @param <resource> new 資源
* @param <int> transparent 如果分配失敗則返回 FALSE
*/
private function transparent($new) {
$transparent = imagecolorallocatealpha($new , 0 , 0 , 0 , 127);
imagealphablending($new , false);
imagefill($new , 0 , 0 , $transparent);
imagesavealpha($new , true);
}

//格式化錯誤輸出
private function halt($message) {
echo $message;
exit();
}
}

LtUpload上傳組件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.