thinkphp realize picture upload function sharing

Source: Internet
Author: User
Tags create index file size root directory

  Image upload is a very common feature in the website. Thinkphp also has its own picture upload Class (UploadFile.class.php) and Picture model Class (Image.class.php). Convenient for us to implement the image upload function, the following is the implementation method

1. We first need to create a table     code as follows: CREATE TABLE IF not EXISTS ' tp_image ' (  ' id ' int (one) not NULL auto_increment, &NB Sp ' image ' varchar NOT NULL,   ' create_time ' int (one) not NULL,   PRIMARY KEY (' id ') Engine=myisam  DEFA ULT Charset=utf8;     2. Then add the configuration in the Conf file (the last configuration is optional, just to facilitate the unified management URL path)     code is as follows: <?php return Array (        ' Url_model '    =>    2,//If your environment does not support PathInfo please set to 3         ' db_ty PE '    =>     ' MySQL ',     '     ' db_host '    => '     ' Localh Ost ',         ' db_name '    =>     ' thinkphp ',         ' Db_us ER '    =>     ' root ',     '     ' db_pwd '    => '     ', &nbsp ;       ' db_port '    =>     ' 3306 ',         ' Db_prefix '   &NBS P;=>     ' tp_ ',           ' show_page_trace ' =>true,        //Display page debug details           ' tmpl_parse_string ' =>  array (//address replacement, using _upload_ directory instead of the root directory UPLOAD directory   &NB Sp       ' __upload__ '    =>  __root__. ' /uploads ',      );?>     3. Add an image module (name can be arbitrarily taken)     code is as follows: <?php     Class Imageaction extends action{                 /**          * CREATE index Entry method          */        Public Function index () {&nbs P           $image =m (' image ');                                  &NBS P $data = $image->order (' create_time desc ')->find ();    //get final upload photos             $this->assigN (' data ', $data);             $this->display ();        } ?>     4. Create the corresponding index view file (index.html)     code as follows: <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "> <title>insert title here</title> <style type=" Text/css ">     #img { height:22px; border: #000 2px solid}     #button {height:30px; width:100px;} </style> </head> <body>     <div class= "result" > Upload allowed file type: gif png jpg image file, and generate 2 thumbnails, where the large image with watermark, will be deleted after the original artwork. </div><br>     <notempty name= "data" ><img src= "__upload__/m_{$data. Image}"/> < IMG src= "__upload__/s_{$data. Image}"/></notempty>     <form action= "__url__/upload" method= " Post "enctype=" Multipart/form-data ">       &NBsp <input type= "file" name= "image" Id= "img"/>         <input type= "Submit" value= "Upload" id= "Butto N ">      </form> </body> </html>     5. Select the picture, click on the Upload button, will jump to the image module upload method , the image module does not have this method now, so we created it     code as follows: <?php     class Imageaction extends action{    &NBSP ;            /**          * CREATE index Entry method          */        Public Function index () {            $image =m (' image ') ;                                   &NB Sp $data = $image->order (' create_time desc ')->find ();    //get final upload picture               var_dump ($data);             $this->assign (' data ', $data);             $this->display ();        }           //If the uploaded file is not empty, jump to _upload method       &NBS P Public function upload () {                   //If not NULL     &NBS P       if (!empty ($_files))             {          &N Bsp     $this->_upload ();                       {    6. Skip to the _upload method if the commit is not NULL , this method implements the image upload function   code as follows: <?php     class Imageaction extends action{          &NBS P      /**          * CREATE index Entry method          */  &NBS P     Public Function index () {            $image =m (' image ');       & nbsp                   &NBSp         $data = $image->order (' create_time desc ')->find ();    //get final upload picture               var_dump ($data);             $this->assign (' data ', $data);             $this->display ();        }                    //If the uploaded file is not empty, jump to _ Upload method         public Function upload () {                &NB Sp  //If not NULL             if (!empty ($_files))             {& nbsp               $this->_upload ();                                         /***          * implementation picture upload          */        Public Function _upload () {          import (' @.org.uploadfile ');            //import upload class             $upload = new UploadFile ();            //Set upload file size             $upload->maxsize            = 3292200;            //Set upload file type             $upload->allowexts &nbsp ;        = explode (', ', ' jpg,gif,png,jpeg ');            //Set up attachments upload catalog             $upload->savepath           = './uploads/';            //settings need to generate thumbnails, only for image files valid             $upload->thumb              = true;            //Set Reference Picture Class Library package path &NBSp           $upload->imageclasspath     = ' @.org.image ';            //setup needs to generate thumbnail file suffix             $upload->thumbpref IX        = ' m_,s_ ';  //production 2 thumbnails            //Set thumbnail maximum width             $upload-&G T;thumbmaxwidth      = ' 400,100 ';            //Set thumbnail maximum height             $upload->thumbmaxheight     = ' 400,100 ';            //Set upload file rule             $upload->saverule           = ' uniqid ';            //delete original             $upload->thumbremoveorigin & nbsp;= true;                           //If upload not successful            if (! $upload->upload ())               {    &NB Sp          //capture upload exception                 $this->error ($uploa D->geterrormsg ());            }              else      &NBSP ;       {               //Get successfully uploaded file information         & nbsp       $uploadList = $upload->getuploadfileinfo ();                                  &NBS P Import picture class                 import (' @.org.image ');                                  /Send M_ thumbnail add watermark, image::water (' Original file path ', ' watermark Image address ')                 Image::water ($uploadList [0][' Savepath ']. ' M_ '. $uploadList [0][' Savename '], App_path. ' Tpl/public/images/logo.png ');                  //Picture name assigned To field image                 $_post[' image ' = $uploadList [0][' Savename '];                         $model  = M (' image ');            //Save current data Object             $data [' image ']   &nbsp ;      = $_post[' image '];             $data [' create_time ']    = now_time;             $list   = $model->add ($data);             if ($list!== false)               {  &N Bsp             $this->success (' Upload image success! ');           &nbsp }              else              {    &NB Sp           $this->error (' Upload image failed! ')                     {           } ;     Upload successfully generated two thumbnails   need to explain:   thinkphp with the picture upload Class (UploadFile.class.php) and Picture model class (Image.class.php), To the full version of the thinkphp package only.   No words need to create a folder in Lib (org), and then go to the official website to download the expansion pack to put the two files in the ORG folder.   Mine is the second situation    
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.