search
HomeBackend DevelopmentPHP TutorialThinkphp upload class implements the code for uploading images

本篇文章给大家带来的内容是关于Thinkphp上传类实现上传图片的代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

thinkphp如何上传图片呢?下面就为大家详细介绍下!

1、封装上传类方法

<?php
//调用上传
public function uploadUser(){
   $banner=$this->uploadYmdImg(&#39;ymd_banner&#39;);
   if(!empty($banner)){
	  $data[&#39;ymd_banner&#39;]=$banner;
   }
}
   /*
 * 封装图片上传
 * */	
public function uploadYmdImg($fileName,$route="banner"){
	if(!empty($_FILES[$fileName][&#39;tmp_name&#39;])){
		    $upload = new \Think\Upload();// 实例化上传类
		    $upload->maxSize   =     3145728 ;// 设置附件上传大小
		    $upload->exts      =     array(&#39;jpg&#39;, &#39;gif&#39;, &#39;png&#39;, &#39;jpeg&#39;);// 设置附件上传类型
		    $upload->rootPath  =      &#39;./Upload/&#39;.$route.&#39;/&#39;; // 设置附件上传根目录
		    // 上传单个文件 
		    $info   =   $upload->uploadOne($_FILES[$fileName]);
		    if(!$info) {// 上传错误提示错误信息
		        $this->error($upload->getError());
		    }else{// 上传成功 获取上传文件信息
		        return C(&#39;TMPL_PARSE_STRING.__YIMUDI__&#39;).&#39;/Upload/&#39;.$route.&#39;/&#39;.$info[&#39;savepath&#39;].$info[&#39;savename&#39;];
		   }			
	}else{
		return NULL;
	}		
}

2、Thinkphp内部定义的上传类

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
namespace Think;
class Upload {
    /**
     * 默认上传配置
     * @var array
     */
    private $config = array(
        &#39;mimes&#39;         =>  array(), //允许上传的文件MiMe类型
        &#39;maxSize&#39;       =>  0, //上传的文件大小限制 (0-不做限制)
        &#39;exts&#39;          =>  array(), //允许上传的文件后缀
        &#39;autoSub&#39;       =>  true, //自动子目录保存文件
        &#39;subName&#39;       =>  array(&#39;date&#39;, &#39;Y-m-d&#39;), //子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组
        &#39;rootPath&#39;      =>  &#39;./Uploads/&#39;, //保存根路径
        &#39;savePath&#39;      =>  &#39;&#39;, //保存路径
        &#39;saveName&#39;      =>  array(&#39;uniqid&#39;, &#39;&#39;), //上传文件命名规则,[0]-函数名,[1]-参数,多个参数使用数组
        &#39;saveExt&#39;       =>  &#39;&#39;, //文件保存后缀,空则使用原后缀
        &#39;replace&#39;       =>  false, //存在同名是否覆盖
        &#39;hash&#39;          =>  true, //是否生成hash编码
        &#39;callback&#39;      =>  false, //检测文件是否存在回调,如果存在返回文件信息数组
        &#39;driver&#39;        =>  &#39;&#39;, // 文件上传驱动
        &#39;driverConfig&#39;  =>  array(), // 上传驱动配置
    );

    /**
     * 上传错误信息
     * @var string
     */
    private $error = &#39;&#39;; //上传错误信息

    /**
     * 上传驱动实例
     * @var Object
     */
    private $uploader;

    /**
     * 构造方法,用于构造上传实例
     * @param array  $config 配置
     * @param string $driver 要使用的上传驱动 LOCAL-本地上传驱动,FTP-FTP上传驱动
     */
    public function __construct($config = array(), $driver = &#39;&#39;, $driverConfig = null){
        /* 获取配置 */
        $this->config   =   array_merge($this->config, $config);

        /* 设置上传驱动 */
        $this->setDriver($driver, $driverConfig);

        /* 调整配置,把字符串配置参数转换为数组 */
        if(!empty($this->config[&#39;mimes&#39;])){
            if(is_string($this->mimes)) {
                $this->config[&#39;mimes&#39;] = explode(&#39;,&#39;, $this->mimes);
            }
            $this->config[&#39;mimes&#39;] = array_map(&#39;strtolower&#39;, $this->mimes);
        }
        if(!empty($this->config[&#39;exts&#39;])){
            if (is_string($this->exts)){
                $this->config[&#39;exts&#39;] = explode(&#39;,&#39;, $this->exts);
            }
            $this->config[&#39;exts&#39;] = array_map(&#39;strtolower&#39;, $this->exts);
        }
    }

    /**
     * 使用 $this->name 获取配置
     * @param  string $name 配置名称
     * @return multitype    配置值
     */
    public function __get($name) {
        return $this->config[$name];
    }

    public function __set($name,$value){
        if(isset($this->config[$name])) {
            $this->config[$name] = $value;
            if($name == &#39;driverConfig&#39;){
                //改变驱动配置后重置上传驱动
                //注意:必须选改变驱动然后再改变驱动配置
                $this->setDriver(); 
            }
        }
    }

    public function __isset($name){
        return isset($this->config[$name]);
    }

    /**
     * 获取最后一次上传错误信息
     * @return string 错误信息
     */
    public function getError(){
        return $this->error;
    }

    /**
     * 上传单个文件
     * @param  array  $file 文件数组
     * @return array        上传成功后的文件信息
     */
    public function uploadOne($file){
        $info = $this->upload(array($file));
        return $info ? $info[0] : $info;
    }

    /**
     * 上传文件
     * @param 文件信息数组 $files ,通常是 $_FILES数组
     */
    public function upload($files=&#39;&#39;) {
        if(&#39;&#39; === $files){
            $files  =   $_FILES;
        }
        if(empty($files)){
            $this->error = &#39;没有上传的文件!&#39;;
            return false;
        }

        /* 检测上传根目录 */
        if(!$this->uploader->checkRootPath($this->rootPath)){
            $this->error = $this->uploader->getError();
            return false;
        }

        /* 检查上传目录 */
        if(!$this->uploader->checkSavePath($this->savePath)){
            $this->error = $this->uploader->getError();
            return false;
        }

        /* 逐个检测并上传文件 */
        $info    =  array();
        if(function_exists(&#39;finfo_open&#39;)){
            $finfo   =  finfo_open ( FILEINFO_MIME_TYPE );
        }
        // 对上传文件数组信息处理
        $files   =  $this->dealFiles($files);    
        foreach ($files as $key => $file) {
            $file[&#39;name&#39;]  = strip_tags($file[&#39;name&#39;]);
            if(!isset($file[&#39;key&#39;]))   $file[&#39;key&#39;]    =   $key;
            /* 通过扩展获取文件类型,可解决FLASH上传$FILES数组返回文件类型错误的问题 */
            if(isset($finfo)){
                $file[&#39;type&#39;]   =   finfo_file ( $finfo ,  $file[&#39;tmp_name&#39;] );
            }

            /* 获取上传文件后缀,允许上传无后缀文件 */
            $file[&#39;ext&#39;]    =   pathinfo($file[&#39;name&#39;], PATHINFO_EXTENSION);

            /* 文件上传检测 */
            if (!$this->check($file)){
                continue;
            }

            /* 获取文件hash */
            if($this->hash){
                $file[&#39;md5&#39;]  = md5_file($file[&#39;tmp_name&#39;]);
                $file[&#39;sha1&#39;] = sha1_file($file[&#39;tmp_name&#39;]);
            }

            /* 调用回调函数检测文件是否存在 */
            $data = call_user_func($this->callback, $file);
            if( $this->callback && $data ){
                if ( file_exists(&#39;.&#39;.$data[&#39;path&#39;])  ) {
                    $info[$key] = $data;
                    continue;
                }elseif($this->removeTrash){
                    call_user_func($this->removeTrash,$data);//删除垃圾据
                }
            }

            /* 生成保存文件名 */
            $savename = $this->getSaveName($file);
            if(false == $savename){
                continue;
            } else {
                $file[&#39;savename&#39;] = $savename;
            }

            /* 检测并创建子目录 */
            $subpath = $this->getSubPath($file[&#39;name&#39;]);
            if(false === $subpath){
                continue;
            } else {
                $file[&#39;savepath&#39;] = $this->savePath . $subpath;
            }

            /* 对图像文件进行严格检测 */
            $ext = strtolower($file[&#39;ext&#39;]);
            if(in_array($ext, array(&#39;gif&#39;,&#39;jpg&#39;,&#39;jpeg&#39;,&#39;bmp&#39;,&#39;png&#39;,&#39;swf&#39;))) {
                $imginfo = getimagesize($file[&#39;tmp_name&#39;]);
                if(empty($imginfo) || ($ext == &#39;gif&#39; && empty($imginfo[&#39;bits&#39;]))){
                    $this->error = &#39;非法图像文件!&#39;;
                    continue;
                }
            }

            /* 保存文件 并记录保存成功的文件 */
            if ($this->uploader->save($file,$this->replace)) {
                unset($file[&#39;error&#39;], $file[&#39;tmp_name&#39;]);
                $info[$key] = $file;
            } else {
                $this->error = $this->uploader->getError();
            }
        }
        if(isset($finfo)){
            finfo_close($finfo);
        }
        return empty($info) ? false : $info;
    }

    /**
     * 转换上传文件数组变量为正确的方式
     * @access private
     * @param array $files  上传的文件变量
     * @return array
     */
    private function dealFiles($files) {
        $fileArray  = array();
        $n          = 0;
        foreach ($files as $key=>$file){
            if(is_array($file[&#39;name&#39;])) {
                $keys       =   array_keys($file);
                $count      =   count($file[&#39;name&#39;]);
                for ($i=0; $i<$count; $i++) {
                    $fileArray[$n][&#39;key&#39;] = $key;
                    foreach ($keys as $_key){
                        $fileArray[$n][$_key] = $file[$_key][$i];
                    }
                    $n++;
                }
            }else{
               $fileArray = $files;
               break;
            }
        }
       return $fileArray;
    }

    /**
     * 设置上传驱动
     * @param string $driver 驱动名称
     * @param array $config 驱动配置     
     */
    private function setDriver($driver = null, $config = null){
        $driver = $driver ? : ($this->driver       ? : C(&#39;FILE_UPLOAD_TYPE&#39;));
        $config = $config ? : ($this->driverConfig ? : C(&#39;UPLOAD_TYPE_CONFIG&#39;));
        $class = strpos($driver,&#39;\\&#39;)? $driver : &#39;Think\\Upload\\Driver\\&#39;.ucfirst(strtolower($driver));
        $this->uploader = new $class($config);
        if(!$this->uploader){
            E("不存在上传驱动:{$name}");
        }
    }

    /**
     * 检查上传的文件
     * @param array $file 文件信息
     */
    private function check($file) {
        /* 文件上传失败,捕获错误代码 */
        if ($file[&#39;error&#39;]) {
            $this->error($file[&#39;error&#39;]);
            return false;
        }

        /* 无效上传 */
        if (empty($file[&#39;name&#39;])){
            $this->error = &#39;未知上传错误!&#39;;
        }

        /* 检查是否合法上传 */
        if (!is_uploaded_file($file[&#39;tmp_name&#39;])) {
            $this->error = &#39;非法上传文件!&#39;;
            return false;
        }

        /* 检查文件大小 */
        if (!$this->checkSize($file[&#39;size&#39;])) {
            $this->error = &#39;上传文件大小不符!&#39;;
            return false;
        }

        /* 检查文件Mime类型 */
        //TODO:FLASH上传的文件获取到的mime类型都为application/octet-stream
        if (!$this->checkMime($file[&#39;type&#39;])) {
            $this->error = &#39;上传文件MIME类型不允许!&#39;;
            return false;
        }

        /* 检查文件后缀 */
        if (!$this->checkExt($file[&#39;ext&#39;])) {
            $this->error = &#39;上传文件后缀不允许&#39;;
            return false;
        }

        /* 通过检测 */
        return true;
    }


    /**
     * 获取错误代码信息
     * @param string $errorNo  错误号
     */
    private function error($errorNo) {
        switch ($errorNo) {
            case 1:
                $this->error = &#39;上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值!&#39;;
                break;
            case 2:
                $this->error = &#39;上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值!&#39;;
                break;
            case 3:
                $this->error = &#39;文件只有部分被上传!&#39;;
                break;
            case 4:
                $this->error = &#39;没有文件被上传!&#39;;
                break;
            case 6:
                $this->error = &#39;找不到临时文件夹!&#39;;
                break;
            case 7:
                $this->error = &#39;文件写入失败!&#39;;
                break;
            default:
                $this->error = &#39;未知上传错误!&#39;;
        }
    }

    /**
     * 检查文件大小是否合法
     * @param integer $size 数据
     */
    private function checkSize($size) {
        return !($size > $this->maxSize) || (0 == $this->maxSize);
    }

    /**
     * 检查上传的文件MIME类型是否合法
     * @param string $mime 数据
     */
    private function checkMime($mime) {
        return empty($this->config[&#39;mimes&#39;]) ? true : in_array(strtolower($mime), $this->mimes);
    }

    /**
     * 检查上传的文件后缀是否合法
     * @param string $ext 后缀
     */
    private function checkExt($ext) {
        return empty($this->config[&#39;exts&#39;]) ? true : in_array(strtolower($ext), $this->exts);
    }

    /**
     * 根据上传文件命名规则取得保存文件名
     * @param string $file 文件信息
     */
    private function getSaveName($file) {
        $rule = $this->saveName;
        if (empty($rule)) { //保持文件名不变
            /* 解决pathinfo中文文件名BUG */
            $filename = substr(pathinfo("_{$file[&#39;name&#39;]}", PATHINFO_FILENAME), 1);
            $savename = $filename;
        } else {
            $savename = $this->getName($rule, $file[&#39;name&#39;]);
            if(empty($savename)){
                $this->error = &#39;文件命名规则错误!&#39;;
                return false;
            }
        }

        /* 文件保存后缀,支持强制更改文件后缀 */
        $ext = empty($this->config[&#39;saveExt&#39;]) ? $file[&#39;ext&#39;] : $this->saveExt;

        return $savename . &#39;.&#39; . $ext;
    }

    /**
     * 获取子目录的名称
     * @param array $file  上传的文件信息
     */
    private function getSubPath($filename) {
        $subpath = &#39;&#39;;
        $rule    = $this->subName;
        if ($this->autoSub && !empty($rule)) {
            $subpath = $this->getName($rule, $filename) . &#39;/&#39;;

            if(!empty($subpath) && !$this->uploader->mkdir($this->savePath . $subpath)){
                $this->error = $this->uploader->getError();
                return false;
            }
        }
        return $subpath;
    }

    /**
     * 根据指定的规则获取文件或目录名称
     * @param  array  $rule     规则
     * @param  string $filename 原文件名
     * @return string           文件或目录名称
     */
    private function getName($rule, $filename){
        $name = &#39;&#39;;
        if(is_array($rule)){ //数组规则
            $func     = $rule[0];
            $param    = (array)$rule[1];
            foreach ($param as &$value) {
               $value = str_replace(&#39;__FILE__&#39;, $filename, $value);
            }
            $name = call_user_func_array($func, $param);
        } elseif (is_string($rule)){ //字符串规则
            if(function_exists($rule)){
                $name = call_user_func($rule);
            } else {
                $name = $rule;
            }
        }
        return $name;
    }

}

相关推荐: 

php实现生成混合验证码与图像验证码并测试(代码)

tp5实现批量上传图片的方法代码

The above is the detailed content of Thinkphp upload class implements the code for uploading images. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor