搜尋
首頁php教程PHP源码tangframework 上传类

tangframework 上传类

May 26, 2016 am 08:20 AM


namespace Tang\Util;
use Tang\Exception\SystemException;
use Tang\Services\FileService;
use Tang\Storage\Drivers\IStorage;

/**
 * 文件上传组件
 * Class Upload
 * @package Tang\Util
 */
class Upload
{
    /**
     * 允许上传的文件后缀
     * @var array
     */
    private $allowExts= array('jpg','jpeg','gif','png','bmp');
    /**
     * 是否安全类型检查
     * @var boolean
     */
    private $allowSafeCheck = true;
    /**
     * 文件后缀名
     * @var string
     */
    private $ext = '';
    /**
     * 上传最大大小 (K为单位 1M=1024K)
     * @var int
     */
    private $maxSize = 1024;
    /**
     * 存储引擎
     * @var IStorage
     */
    protected $storage;

    /**
     * @param IStorage $storage 存储引擎
     * @param int $maxSize 最大尺寸
     * @param bool $allowSafeCheck 是否允许安全检查
     * @param array $exts 允许上传的后缀
     */
    public function __construct(IStorage $storage,$maxSize = 0,$allowSafeCheck = true,array $exts=array())
    {
        $this->setStorage($storage)
               ->setMaxSize($maxSize)->setAllowSafe($allowSafeCheck);
        if($exts)
        {
            $this->setAllowExts($exts);
        }
    }
    /**
     * 设置上传的最大KB
     * 为0的时候则设置为无限大小
     * @param int $maxSize
     * @return $this
     */
    public function setMaxSize($maxSize = 0)
    {
        $maxSize = (int)$maxSize;
        $this->maxSize = $maxSize > 0 ? $maxSize : 0;
        return $this;
    }
    /**
     * 设置允许上传的文件后缀数组
     * @param array $exts
     * @return $this
     */
    public function setAllowExts(array $exts)
    {
        $this->allowExts = $exts;
        return $this;
    }
    /**
     * 设置是否允许安全类型检查
     * @param boolean $allowSafeCheck
     * @return $this
     */
    public function setAllowSafe($allowSafeCheck = true)
    {
        $this->allowSafeCheck = $allowSafeCheck;
        return $this;
    }
    /**
     * 设置存储引擎
     * @param IStorage $storage
     * @return $this
     */
    public function setStorage(IStorage $storage)
    {
        $this->storage = $storage;
        return $this;
    }

    /**
     * 如果file控件里面类似于file[]这样的数组信息时候,如果需要用自己定义的地址的时候。
     * $fileName则需要传递一个数组对应上传的文件
     * @param string $filed 上传的字段名 file控件里面的name
     * @param mixed $fileName 生成的文件名 不填写的话为系统自动生成文件地址
     * @return array
     * @throws NotFoundFileUploadException
     * @throws UploadErrorException
     * @throws UploadSafeCheckException
     */
    public function move($filed,$fileName=null)
    {
        if(!isset($_FILES[$filed]))
        {
            throw new NotFoundFileUploadException($filed);
        }
        $uploadFile = $_FILES[$filed];
        if(is_array($uploadFile['name']))
        {
            $fileStructs = array();
            if(!is_array($fileName))
            {
                $fileName = array();
            }
            foreach($uploadFile['name'] as $key => $value)
            {
                $fileStructs[$key] = $this->uploadHandle(array('name' => $value,'type' => $uploadFile['type'][$key],'tmp_name' => $uploadFile['tmp_name'][$key],'error' => $uploadFile['error'][$key],'size' => $uploadFile['size'][$key]),isset($fileName[$key]) && $fileName[$key] ? $fileName[$key]:'');
            }
            return $fileStructs;
        } else
        {
            return $this->uploadHandle($uploadFile,$fileName);
        }
    }
    private function uploadHandle($uploadFile,$fileName='')
    {
        if($uploadFile['error'] > 0)
        {
            throw new UploadErrorException('File upload error '.$uploadFile['error'],null,50001+$uploadFile['error']);
        } else if(!is_uploaded_file($uploadFile['tmp_name']))
        {
            throw new UploadErrorException('Illegal file upload!',null,50010);
        }
        //判断后缀
        $this->ext = FileService::getService()->getExtension($uploadFile['name']);
        if($this->allowExts && !in_array($this->ext, $this->allowExts))
        {

            throw new UploadSafeCheckException('Only allowed to upload the [%s] file!',array(implode(',', $this->allowExts)),50001);
        }
        if($this->maxSize > 0)
        {
            $maxSize = 1024 * $this->maxSize;
            if($uploadFile['size'] > $maxSize )
            {
                throw new UploadErrorException('Upload file size is [%d byte], is greater than the set of [%d byte]!',array($uploadFile['size'],$maxSize),50000);
            }
        }
        //安全类型检查
        if($this->allowExts && in_array($this->ext, array('jpeg','jpg','gif','png','bmp')) && !$this->picScan($uploadFile['tmp_name']))
        {
            throw new UploadSafeCheckException('The uploaded file is not a [%s] file!',array($this->ext),50011);
        }
        !$fileName && $fileName = $this->createFilePath();
        $fileStruct = $this->storage->putFile($uploadFile['tmp_name'],$fileName);
        $fileStruct['name'] = $uploadFile['name'];
        return $fileStruct;
    }
    /**
     * 检查文件是否是一个图片
     * @param string $fileName
     * @return boolean
     */
    private function picScan($fileName)
    {
        $tempImageSize = @getimagesize($fileName);
        list($tempWidth, $tempHeight, $tempType) = (array)$tempImageSize;
        $tempSize = $tempWidth * $tempHeight;
        if($tempSize > 16777216 || $tempSize < 4 || empty($tempType) || strpos($tempImageSize[&#39;mime&#39;], &#39;flash&#39;) > 0)
        {
            return false;
        }
        return true;
    }
    /**
     * 构建上传路径
     */
    private function createFilePath()
    {
        return date(&#39;ym/d/&#39;).sha1(uniqid(mt_rand(),1)).&#39;.&#39;.$this->ext;
    }
}

                   

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能