首頁 後端開發 php教程 thinkphp檔案上傳類

thinkphp檔案上傳類

Aug 08, 2016 am 09:31 AM
file nbsp return this

/**
 *這是一個文件上傳類,用於處理上傳的文件,圖片等,可以自動產生縮圖,添加浮水印
*/
// +---------------------------------- --------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +---------------------------------------------- ------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +-- -------------------------------------------------- ------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +------ -------------------------------------------------- --------------
// | Author: hxsml
// +------------------------- ---------------------------------------------
// $Id : UploadFile.class.php v1.0
/**
 +------------------------------------------------ ------------------------------
 * 檔案上傳類別
 * 
 * 修改:
 *  多檔案上傳時,fileinfo以表單名字為key的陣列
 +-------------------------------------------------- --------------------------------------
 * @category   ORG
 * @package  ORG
 * @subpackage Net
 * @author    hxsml 
 * @version   v1.0
 +----------------------------------- -------------------------------------------
 */
class UploadFile {//類別定義開始
    // 上傳檔案的最大
    public $maxSize = -1;
    // 是否支援多重檔案 // 是否支援多重檔案上傳
    public $supportMulti = true;
    // 允許上傳的檔案後綴
    //  留空不作後綴檢查
    public $allowExts =  留空不作後綴檢查
    public $allowExts = arra(); public $allowTypes = array();
    // 使用對上傳圖片進行縮圖處理
    public $thumb   =  false;
    // 圖庫類別包路徑
•   public $imClass    // 圖…略圖最大寬度
    public $thumbMaxWidth;
    // 縮圖最大高度
    public $thumbMaxHeight;
    // 縮略圖前綴🠎 = public Suffix  =  '';
    // 縮圖保存路徑
    public $thumbPath = '';
    // 縮圖檔案名稱
    public $thumbFile

=

'';壓縮圖片檔上傳
public $zipImages = false;    // 啟用子目錄儲存檔案    public $autoSub   =  false;    // 子目錄建立方式可使用 hash;     public $hashLevel =  1; // hash的目錄層級
    // 上傳檔案保存路徑
    public $savePath = '';
    public $auCheckal = truetrue; $uploadReplace = false;
    // 上傳檔案命名規則
    // 例如可以是time uniqid com_create_guid 等
    // 必須是一個不需要任何參數的函式名稱可以使用自訂功能

'
'o
'') // 上傳檔案Hash規則函數名稱
    // 例如可以是md5_file sha1_file 等
    public $hashType = 'md5_file';
    // 錯誤訊息  uploadFileInfo ;
    /**
     +------------------------------------------------ ----------
     * 架構函數
     +---------------------------------- ------------------------
     * @access public
     +------------------ ---------------------------------------     */    public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='') {
  . !empty($maxSize) && is_numeric($maxSize)) {
            $this->maxSize = $maxSize;
        }🠎)  if(is_array($allowExts)) {
                $this ->allowExts = array_map('strtolower',$allowExts);
            }else {
                $this->allowExts =explode(',',strtolower($allowExts));
         類型 } )) {
            if(is_array ($allowTypes)) {
                $ 此->allowTypes = array_map('strtolower',$allowTypes);
            }else {
              ) $  }
        }
        if(!空($saveRule )) {
            $this->saveRule = $saveRule;
        }else{
       
       }
       $this->savePath = $savePath;
  } /**     +------------------------------------------------ ----------     * 上傳一份檔案     +--------------------------------- -------------------------
     * @access public
     +------------------ ------------------------------------------
     * @param mixed $name 資料
     * @param string $value  資料表名
     +---------------------------------------- ------------------
     * @return string
     +------------------------ ---------------------------------
     * @throws ThinkExecption
     +---------- ------------------------------------------------
     */
    乾燥函數save($file) {
        $filename = $file['savepath'].$file['savename'];
        if(Replace!this-load filename)) {
              // 不覆寫同名檔案
            $this->error

= 🠎'檔案已存在!      }
        // 若是圖片檔案偵測檔案格式
        if ( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file ['tmp_name'])) {
            $this->error = '非法檔案';
            return false;            return false; '], $this->auto_charset($filename,' utf-8','gbk'))) {
            $this->error = '檔案上傳儲存錯誤!';
            return false;
        }
        if($this->thumb && in_array(strtolower($file['extension)$file['arraension] in_array(strtolower($file'g')',$file['arraension'],_array(strtolower($file'g',)'pfile' png'))) {
            $image =  getimagesize($filename);
            if(false !== $image) {🠎 為文件                   $thumbWidth

= 爆炸(',', $this ->thumbMaxWidth);                $thumbHeight
=explode(',',$this->thumbMaxHeight)explode(',',$this->thumbMaxHeight); =
explode( ',',$ this->thumbPrefix );              $thumbSuffix =爆炸(',',$ this-> thumbsuffix);$thumbfile
=
Explode(',',$ this-> thumbfile);$ thumbpath = $ thumbpath = $thumbfile; thumbpath?  $realFilename  =  $this->autoSub?basename ($ 檔案['savename'] ):$file[' savename'];                for($i=0,$len=count($thumbWidth); $i    

$thumbPath.$thumbPrefix [$i].substr ($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
            ,$thumbname,'' ,$thumbWidth[$i],$thumbHeight[$i],true);
                }
     this               // 之後產生了刪除原圖
                   unlink($ filename);                } }        }        if($    }
        return true;
    }
圖片    /**
     +------------------------------------------------ ----------
     * 上傳所有檔案
     +--------------------------------- -------------------------
     * @access public
     +------------------ ------------------------------------------
     * @param string $savePath  上傳檔案儲存路徑
     +----------------------------------------------- -----------
     * @return string
     +-------------------------------- --------------------------
     * @throws ThinkExecption
     +----------------- -----------------------------------------
     */
    public function upload ( $儲存路徑='' ) {
        //如果沒有指定儲存檔案名,則由系統預設
        if(empty($savePath))
       Path  $savePath = $
        // 檢查上傳目錄
        if(!is_dir($savePath)) {
            ) {
                  $save路徑

=

base64_decode( $ savePath);
            }else{
                // 嘗試建立目錄
               $this->error  = '上傳目錄'.$save Path.'不存在';
                   return false;
}
            }
        }else {
            if(!is_writeable($savePath)) {
                $this->羅  return false;
            }
        }
        $fileInfo = array();
$isUpload   = false;
        // 取得上傳的檔案資訊
        // 對$_FILES陣列資訊處理
        $filesthis_  foreach($files as $key => $file) {
            //過濾無效的上傳            if(!empty($file['name'])) {     登錄文件      $file['key']          =  $key;                $ file['extension']  = $this->getExt($file['name']);                $file['savepath']   = $save ($ file);
                // 自動檢查配件
                if($this->  
                        return false;
                      if(!$ this->save($file)) return false;
                if(function_exists($this->hashType)) {
       類型 $                $file['hash']   =  $fun($this- >auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
                }              }          unset( $file['tmp_name'],$file['error']);
                $fileInfo[$key] = $file;
                  }
        if($isUpload) {
            $this-> uploadFileInfo = $fileInfo;
            return true;
        }else {
        5        return false;
        }
    }
    /**
     +------------------------------------------------ ----------
     * 上傳單一上傳欄位中的檔案支援多重附件
     +-------------------------- --------------------------------
     * @access public
     +----------- -----------------------------------------------
     * @ param array $file  上傳檔案資料
     * @param string $savePath  上傳檔案儲存路徑
     +------------------------------ ----------------------------
     * @return string
     +--------------- -------------------------------------------
     * @throws ThinkExecption
     + -------------------------------------------------- --------
     */
    public function uploadOne($file,$savePath=''){
        //如果不指定儲存檔案$savePath = $this->savePath;
        // 檢查上傳目錄
        if(!is_dir($savePath)) {
        嘗試創建目錄 000000000 目錄  {
                $this->error  =  '上傳目錄'.$savePath.'不存在';
                return false;
            }
 )) {
                $this->error  =  '上傳目錄'.$savePath.'不可寫';
                return false;
            }
       ) {
            $fileArray = array();
            if(is_array($file[' name'])) {
               $keys = array_keys($file);
                    for ($i=0; $i                   foreach ($keys as $key)
                        }
            }else{
                $fileArray[] = $file;
            }
            $info =  array();     檔案的擴充資訊                $file['extension']  = $this->getExt($file ['name']);                $file['savepath']   = $savePath;                 // 自動檢查配件
                if($this- >autoCheck) {
                    if(!$this->check($file))
             }
                //儲存上傳檔案
                if(!$this->  function_exists($this->hashType)) {
                    $fun =  $this->hashType;
   to_charset($file['savepath'].$file[' savename'],'utf-8','gbk'));
                }
                unset($file['tmp_name'],$file['error']);
                  // 回傳的檔案資訊
            return $info;
        }else {
         $ 。 ='gbk', $to='utf -8') {
        $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
        $to = strtoupper($to) == 'UTF8' ? ' $to;
        if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) { 內容或非字串標量則不轉換
            return $fContents;
        }
        if (is_string($fents)) {funcfents) { coding')) {
                return mb_convert_encoding($fContents, $to, $from);
            } elseif (function_exists('iconv')) {
                return iconv($from, $, $ffroms), $f Cont              return $fContents;
            }
        }   ($fContents as $key => $val) {
                $_key = $this->auto_charset($key, $from, $to);
   _$p. from, $to);
                if ($key != $_key)
                           return $fContents;
        }
        else {
        
/**
     +------------------------------------------------ ----------
     * 轉換上傳檔案陣列變數為正確的方式
     * 
     * 修改:
     *  當設定name=upload[]時,key為「包含多個」,   *  當設定name=upload[]。
     *  件訊息的以數位化為引多維數組,name=upload1...,key為對應
     *  的名字
     +--------------------- -------------------------------------
     * @access private
     +------ -------------------------------------------------- --
     * @param array $files  上傳的檔案變數
     +----------------------------------- -----------------------
     * @return array
     +-------------------- --------------------------------------
     */
    private function dealFiles($files) {
       $fileArray = array();
       foreach ($files as $file.> $名稱' ])) {
               $keys = array_keys($file);
                     for ($i=0; $i                   foreach ($keys as $key)
                            }
           }else{
               $fileArray[$field] = $file;
           }
       }
       return $fileArray;
   }
    /**
     +------------------------------------------------ ----------
     * 取得錯誤代碼資訊
     +-------------------------------- --------------------------
     * @access public
     +---------------- -----------------------------------------
     * @param string $errorNo  錯誤號碼
     +------------------------------------------------ ----------
     * @return void
     +-------------------------------- -------------------------
     * @throws ThinkExecption
     +------------------ ----------------------------------------
     */
    protected function error($errorNo) {
         switch($errorNo) { $this->error = '上傳的檔案超過了php.ini 中upload_max_filesize 選項限制的值';
                break;
            case 2:
                          break;
            case 3:
               $this->error = '檔案->只有部分上傳';
                break;
            case 4:
              break;
            case 6:
                $this->error = '找不到暫時資料夾';
                break;
            case 7:
           break;
            default:
                $this->error = '未知上傳錯誤!';
        }
        return ;
    }
    /**
     +------------------------------------------------ ----------
     * 依上傳檔案命名規則取得保存檔案名稱
     +--------------------------- -------------------------------
     * @access private
     +------------ ----------------------------------------------
     * @param string $filename 資料
     +-------------------------------------------- --------------
     * @return string
     +----------------------------- -----------------------------
     */
    private function getSaven (this.

        if(empty($rule)) { //沒有定義命名規則,則保持檔案名稱不變            //$saveName = $filename['name'];


$saveName = date('YmdHis').rand().".".$filename ['extension'];        }else{

            if(function_exists($ru             $saveName = $rule().".".$filename[ 'extension'];            }else {
                //使用給定的檔案名稱為識別號碼 $. $.
            }
        }
        if($this- >autoSub) {
            // 使用子目錄儲存檔案
            $filename['savename'] = $saveName;    Name $filename['savename'] = $saveName;  Name $Name $Name $Name-name $name.
        }
        return $ saveName;
    }
    /**
     +------------------------------------------------ ----------
     * 取得子目錄的名稱
     +------------------------------- ---------------------------
     * @access private
     +---------------- ------------------------------------------
     * @param array $file  上傳的文件資訊
     +--------------------------------------------- -------------
     * @return string
     +------------------------------ ----------------------------
     */
    private function getSubName($file) {
                    $dir   =  date($this->dateFormat, time());
                break;
            case 'hash':
   $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;
        }
        >checkSize($file[' size'])) {
            $this->error = '上傳檔案大小不符! ';
            return false;
        }
        //檢查檔案Mime類型
     $this->error = '上傳檔案MIME類型不允許! ';
            return false;
        }
        //檢查檔案類型
     $this->error ='上傳檔案類型不允許';
return false;
        }
        //檢查是否合法上傳
        if(!$this->checkUpload($file['tmp_name'])) {🠎>  ';
            return false;
        }
        return true;
  }
  類型 /  if(!empty($this->allowTypes))
           返回in_array( strtolower ($type),$this->allowTypes);
        return true;
    }
    /**
     +------------------------------------------------ ----------
     * 檢查上傳的檔案類型是否合法
     +----------------------------- -----------------------------
     * @access private
     +-------------- --------------------------------------------
     * @param string $ type 資料
     +---------------------------------------------- ------------
     * @return boolean
     +------------------------------- ---------------------------
     */
    私有函數
            return in_array(strtolower($ext),$this->allowExts,true);
        return true;
   }
) 私有函數**        return !( $大小> $這個->最大大小) || (-1 == $this->maxSize);
    }
    /**
     +------------------------------------------------ ----------
     * 檢查上傳的文件後綴是否合法
     +----------------------------- -----------------------------
     * @access private
     +-------------- --------------------------------------------
     * @param string $ ext 字尾名
     +--------------------------------------------- -------------
     * @return boolean
     +------------------------------ ----------------------------
     */
    private function checkUpload($filename) {
    private function checkUpload($filename) {
    private function checkUp }
    /**
     +------------------------------------------------ ----------
     * 檢查檔案大小是否合法
     +------------------------------- ---------------------------
     * @access private
     +---------------- ------------------------------------------
     * @param integer $size 數據
     +------------------------------------------------ ----------
     * @return boolean
     +--------------------------------- -------------------------
      */
    private function getExt($filename) {
        $pathinfo = pathinfo($filename);   info    $pathinfo = pathinfo($filename);
    /**
     +------------------------------------------------ ----------
     * 取得上傳文件的資訊
     +------------------------------- ---------------------------
     * @access public
     +---------------- ------------------------------------------
     * @return array
     +- -------------------------------------------------- -------
     */
    public function getUploadFileInfo() {
        return $this->uploadFileInfo;
         return $this->error;
    }
}
以上就介紹了thinkphp檔案上傳類,包括了方面的內容,希望對PHP教學有興趣的朋友有幫助。


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡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脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

解決方法:您的組織要求您更改 PIN 碼 解決方法:您的組織要求您更改 PIN 碼 Oct 04, 2023 pm 05:45 PM

解決方法:您的組織要求您更改 PIN 碼

Windows 11 上調整視窗邊框設定的方法:變更顏色和大小 Windows 11 上調整視窗邊框設定的方法:變更顏色和大小 Sep 22, 2023 am 11:37 AM

Windows 11 上調整視窗邊框設定的方法:變更顏色和大小

如何在 Windows 11 上變更標題列顏色? 如何在 Windows 11 上變更標題列顏色? Sep 14, 2023 pm 03:33 PM

如何在 Windows 11 上變更標題列顏色?

OOBELANGUAGE錯誤Windows 11 / 10修復中出現問題的問題 OOBELANGUAGE錯誤Windows 11 / 10修復中出現問題的問題 Jul 16, 2023 pm 03:29 PM

OOBELANGUAGE錯誤Windows 11 / 10修復中出現問題的問題

Windows 11 上啟用或停用工作列縮圖預覽的方法 Windows 11 上啟用或停用工作列縮圖預覽的方法 Sep 15, 2023 pm 03:57 PM

Windows 11 上啟用或停用工作列縮圖預覽的方法

Windows 11 上的顯示縮放比例調整指南 Windows 11 上的顯示縮放比例調整指南 Sep 19, 2023 pm 06:45 PM

Windows 11 上的顯示縮放比例調整指南

10種在 Windows 11 上調整亮度的方法 10種在 Windows 11 上調整亮度的方法 Dec 18, 2023 pm 02:21 PM

10種在 Windows 11 上調整亮度的方法

如何在Safari中關閉iPhone的隱私瀏覽身份驗證? 如何在Safari中關閉iPhone的隱私瀏覽身份驗證? Nov 29, 2023 pm 11:21 PM

如何在Safari中關閉iPhone的隱私瀏覽身份驗證?

See all articles