Thinkphp Upload class implementation code to upload pictures

Source: Internet
Author: User
This article brings to you the content is about thinkphp upload class implementation of the upload image code, there is a certain reference value, the need for a friend can refer to, I hope you have some help.

thinkphp How to upload pictures? Here is a detailed introduction to you!

1. Package Upload class method

<?php//Call upload Public Function Uploaduser () {   $banner = $this->uploadymdimg (' Ymd_banner ');   if (!empty ($banner)) {  $data [' Ymd_banner ']= $banner;   }}   /* * Package image upload * */public function uploadymdimg ($fileName, $route = "banner") {if (!empty ($_files[$fileName] [' tmp_name '])) {    $upload = new \think\upload ();//Instantiate upload class    $upload->maxsize   =     3145728;//Set attachment upload size    $upload Exts      =     Array (' jpg ', ' gif ', ' PNG ', ' jpeg ');//Set attachment upload type    $upload->rootpath  =      './upload/'. $route. ' /'; Set attachments upload root directory    //upload Single file     $info   =   $upload->uploadone ($_files[$fileName]);    if (! $info) {//Upload error message        $this->error ($upload->geterror ());    } else{//upload successfully upload file information        return C (' tmpl_parse_string.__yimudi__ '). ' /upload/'. $route. ' /'. $info [' Savepath ']. $info [' Savename '];}   } Else{return NULL;}}

2, thinkphp internal definition of the upload class

<?php//+----------------------------------------------------------------------//| thinkphp [WE CAN do it JUST THINK it]//+----------------------------------------------------------------------//| Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.//+--------------------------------------------------         --------------------namespace Think;class Upload {/** * default upload configuration * @var array */private $config = Array ( ' mimes ' = = Array (),//Allow upload of file MIME type ' maxSize ' = + 0,//upload file size limit (0-No limit) ' exts ' = = Array (),//allow upload of file suffix ' autosub ' = = true,//Auto subdirectory save file ' subname ' = = array       (' Date ', ' y-m-d '),//subdirectory creation mode, [0]-function name, [1]-parameter, multiple parameters using array ' rootpath ' + './uploads/',//Save root path ' Savepath ' = = ',//save path ' savename ' = = Array (' uniqid ', '),//upload file naming rules, [0]-function name, [1]-parameter, multiple arguments using array ' Save Ext ' = = ',//File save suffix, empty use original suffix ' replace ' = False,//exists with the same name whether to overwrite ' hash ' + true,//whether to generate hash code ' callback ' = false,//detect if the file exists callback, if present    Returns the file information array ' driver ' + ',//File upload driver ' driverconfig ' = = Array (),//upload drive configuration); /** * Upload Error message * @var String */private $error = ';    Upload error message/** * Upload Driver instance * @var Object */private $uploader; /** * Construction method for constructing an upload instance * @param array $config configuration * @param string $driver The upload driver local-local upload driver to use, FTP-FTP upload driver * /Public Function __construct ($config = Array (), $driver = ", $driverConfig = null) {/* get configuration */$this-&G        T;config = Array_merge ($this->config, $config);        /* Set Upload driver */$this->setdriver ($driver, $driverConfig);                /* Adjust the configuration to convert the string configuration parameter to an array */if (!empty ($this->config[' mimes ')) {if (is_string ($this->mimes)) {            $this->config[' mimes '] = explode (', ', $this->mimes); } $this->config[' mimes ' = arrAy_map (' Strtolower ', $this->mimes); } if (!empty ($this->config[' exts ')) {if (is_string ($this->exts)) {$this->config[            ' exts '] = explode (', ', $this->exts);        } $this->config[' exts ' = Array_map (' Strtolower ', $this->exts);  }}/** * Use $this->name to get configuration * @param string $name configuration name * @return Multitype Configuration value */public    function __get ($name) {return $this->config[$name];  Public Function __set ($name, $value) {if (Isset ($this->config[$name])) {$this->config[$name] =            $value; if ($name = = ' Driverconfig ') {//Change drive configuration after reset upload driver//NOTE: You must select Change driver and then change Drive configuration $this             Setdriver ();    }}} Public function __isset ($name) {return isset ($this->config[$name]); }/** * Gets the last upload error message * @return string error message */Public function GetError () {return $this-> error; /** * Upload a single file * @param array of $file files * @return The file information after the successful upload of the array * * Public function Uplo        Adone ($file) {$info = $this->upload (Array ($file)); Return $info?    $info [0]: $info; /** * Upload file * @param file information array $files, usually $_files array */Public function upload ($files = ") {if (' =        = = $files) {$files = $_files; } if (empty ($files)) {$this->error = ' no uploaded file!            ';        return false; }/* detects the upload root directory */if (! $this->uploader->checkrootpath ($this->rootpath)) {$this->error =            $this->uploader->geterror ();        return false; }/* Check the Upload directory */if (! $this->uploader->checksavepath ($this->savepath)) {$this->error = $            This->uploader->geterror ();        return false;        }/* Detect and upload files individually */$info = array (); if (function_exists (' Finfo_open ')) {$finfo   = Finfo_open (Fileinfo_mime_type);            }//To the uploaded file array information processing $files = $this->dealfiles ($files);            foreach ($files as $key = + $file) {$file [' name '] = strip_tags ($file [' name ']);            if (!isset ($file [' key ')]) $file [' key '] = $key;  /* Get file types by extension to resolve problems with the Flash upload $files array return file type Error */if (Isset ($finfo)) {$file [' type '] = Finfo_file            ($finfo, $file [' tmp_name ']);            }/* Get upload file suffix, allow upload no suffix file */$file [' ext '] = pathinfo ($file [' name '], pathinfo_extension);            /* File Upload detection */if (! $this->check ($file)) {continue;                }/* Gets the file hash */if ($this->hash) {$file [' md5 '] = md5_file ($file [' tmp_name ']);            $file [' sha1 '] = sha1_file ($file [' tmp_name ']);            }/* Call the callback function to detect if the file exists */$data = Call_user_func ($this->callback, $file); if ($this->callbaCK && $data) {if (File_exists ('. ').                    $data [' path ']) {$info [$key] = $data;                Continue            }elseif ($this->removetrash) {call_user_func ($this->removetrash, $data);//delete trash according to}            }/* Generate save File name */$savename = $this->getsavename ($file);            if (false = = $savename) {continue;            } else {$file [' savename '] = $savename;            }/* Detects and creates subdirectories */$subpath = $this->getsubpath ($file [' name ']);            if (false = = = $subpath) {continue;            } else {$file [' savepath '] = $this->savepath. $subpath;            }/* Strict detection of image files */$ext = Strtolower ($file [' ext ']); if (In_array ($ext, Array (' gif ', ' jpg ', ' jpeg ', ' BMP ', ' png ', ' SWF '))) {$imginfo = getimagesize ($file [' Tmp_name ']                ); if (Empty ($imginfo)|| ($ext = = ' gif ' && empty ($imginfo [' bits '])) {$this->error = ' Illegal image file!                    ';                Continue                }/* Save the file and record the file that was successfully saved */if ($this->uploader->save ($file, $this->replace)) {                unset ($file [' Error '], $file [' tmp_name ']);            $info [$key] = $file;            } else {$this->error = $this->uploader->geterror ();        }} if (Isset ($finfo)) {finfo_close ($finfo); } return empty ($info)?    False: $info; }/** * Convert the uploaded file array variable to the correct way * @access private * @param array $files uploaded file variable * @return array * */pri        vate function Dealfiles ($files) {$fileArray = array ();        $n = 0; foreach ($files as $key = + $file) {if (Is_array ($file [' name '])) {$keys = Array_keys ($fi                Le);                $count = count ($file [' name ']); For($i =0; $i < $count; $i + +)                    {$fileArray [$n] [' key '] = $key;                    foreach ($keys as $_key) {$fileArray [$n][$_key] = $file [$_key][$i];                } $n + +;               }}else{$fileArray = $files;            Break    }} return $fileArray; }/** * Set upload driver * @param string $driver drive name * @param array $config Drive configuration */Private function set        Driver ($driver = null, $config = null) {$driver = $driver?: ($this->driver?: C (' File_upload_type ')); $config = $config?        : ($this->driverconfig?: C (' upload_type_config ')); $class = Strpos ($driver, ' \ \ ')?        $driver: ' think\\upload\\driver\\ '. Ucfirst (Strtolower ($driver));        $this->uploader = new $class ($config);        if (! $this->uploader) {E ("There is no upload driver: {$name}"); }}/** * Check the uploaded file * @param array $file file information */private function Check ($file) {/* File upload failed, catch error code */if ($file [' ERROR ']) {$this->error ($file [' ERROR ')            ]);        return false; }/* Invalid upload */if (empty ($file [' name '])) {$this->error = ' Unknown upload error!        '; }/* Check for legal uploads */if (!is_uploaded_file ($file [' tmp_name ')]) {$this->error = ' illegally uploading files!            ';        return false; }/* Check file Size */if (! $this->checksize ($file [' size ']) {$this->error = ' upload file size does not match!            ';        return false; }/* Check file MIME type *///todo:flash the uploaded file gets the MIME type Application/octet-stream if (! $this->checkmime ($fi le[' type ')) {$this->error = ' upload file MIME type not allowed!            ';        return false;            }/* Check the file suffix */if (! $this->checkext ($file [' ext ')]) {$this->error = ' upload file suffix not allowed ';        return false;    }/* Pass Detect */return true; }/** * Get error code information * @param string $Errorno Error number */Private Function error ($ERRORNO) {switch ($errorNo) {Case 1: $th Is->error = ' uploaded file exceeds the value of upload_max_filesize option limit in php.ini!                ';            Break Case 2: $this->error = ' the size of the uploaded file exceeds the value specified in the Max_file_size option in the HTML form!                ';            Break Case 3: $this->error = ' file is only partially uploaded!                ';            Break Case 4: $this->error = ' no files were uploaded!                ';            Break Case 6: $this->error = ' Can't find the Temp folder!                ';            Break Case 7: $this->error = ' File write Failed!                ';            Break Default: $this->error = ' Unknown upload error!        '; }}/** * Check file size is valid * @param integer $size data */Private Function checksize ($size) {return! ($size > $this->maxsize) | |    (0 = = $this->maxsize);  }/** * Check if the uploaded file MIME type is valid * @param string $mime data */  Private Function Checkmime ($mime) {return empty ($this->config[' mimes '))? True:in_array (Strtolower ($mime),    $this->mimes); }/** * Check that the uploaded file suffix is valid * @param string $ext suffix */private function Checkext ($ext) {return empty ($ this->config[' exts ')?    True:in_array (Strtolower ($ext), $this->exts); /** * Save File name * @param string $file file information according to the upload file naming rule */Private function Getsavename ($file) {$ru        Le = $this->savename; if (empty ($rule)) {//Leave file name unchanged/* Resolve pathinfo Chinese file name bug */$filename = substr (PathInfo ("_{$file [' Name ']}            ", Pathinfo_filename), 1);        $savename = $filename;            } else {$savename = $this->getname ($rule, $file [' name ']); if (empty ($savename)) {$this->error = ' file naming rule Error!                ';            return false; }/* File save suffix, support force change file suffix */$ext = empty ($this->config[' Saveext ')? $file [' ext ']: $thisSaveext; Return $savename. '.' .    $ext; /** * Gets the name of the subdirectory * @param array $file uploaded file information */Private Function Getsubpath ($filename) {$SUBPA        th = ";        $rule = $this->subname; if ($this->autosub &&!empty ($rule)) {$subpath = $this->getname ($rule, $filename).            '/'; if (!empty ($subpath) &&! $this->uploader->mkdir ($this->savepath. $subpath)) {$this->err                or = $this->uploader->geterror ();            return false;    }} return $subpath;            /** * Gets the file or directory name according to the specified rule * @param array $rule rule * @param string $filename The original file name * @return string        File or directory name */Private Function GetName ($rule, $filename) {$name = ';            if (Is_array ($rule)) {//array rule $func = $rule [0];            $param = (Array) $rule [1]; foreach ($param as & $value) {$value = Str_replace (' __file__ ', $filename, $value);        } $name = Call_user_func_array ($func, $param);            } elseif (Is_string ($rule)) {//String rule if (function_exists ($rule)) {$name = Call_user_func ($rule);            } else {$name = $rule;    }} return $name; }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.