thinkphp to achieve picture upload function sharing

  • 2021-01-14 05:45:41
  • OfStack

1. We need to create a table first


CREATE TABLE IF NOT EXISTS `tp_image` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(200) NOT NULL,
  `create_time` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

2. Then add the configuration to the conf file (the last configuration is optional, only for the convenience of managing the URL path)


<?php
return array(
        'URL_MODEL'    =>    2, //  If your environment doesn't support it PATHINFO  Please set to 3
        'DB_TYPE'    =>    'mysql',
        'DB_HOST'    =>    'localhost',
        'DB_NAME'    =>    'thinkphp',
        'DB_USER'    =>    'root',
        'DB_PWD'    =>    '',
        'DB_PORT'    =>    '3306',
        'DB_PREFIX'    =>    'tp_',

        'SHOW_PAGE_TRACE' =>true,        // Display page debugging details 

        'TMPL_PARSE_STRING' =>  array( //  Address to replace , with _UPLOAD_ directory   Instead of   The root directory Upload directory 
         '__UPLOAD__'    =>  __ROOT__.'/Uploads',
     ),
);
?>

3. Add 1 Image module (name can be arbitrarily chosen)


<?php
    class ImageAction extends Action{        

        /**
         *  create index  Entry method 
         */
        public function index(){
            $image=M('Image');                       
            $data=$image->order('create_time desc')->find();    // Get the last uploaded image 
            $this->assign('data',$data);
            $this->display();
        } 
?>

4. Create the corresponding index view file (index.html)


<!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" > File types allowed for uploading: gif png jpg  Image file and generated 2 A thumbnail image, in which the large image with watermark, will delete the original image after generation. </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">
        <input type="file" name="image" id="img"/>
        <input type="submit" value=" upload " id="button"> 
    </form>
</body>
</html>

5. Select the image, click the "Upload" button, and it will jump to the upload method of Image module. This method is not available in Image module, so we create it


<?php
    class ImageAction extends Action{        

        /**
         *  create index  Entry method 
         */
        public function index(){
            $image=M('Image');                        
            $data=$image->order('create_time desc')->find();    // Get the last uploaded image 

            var_dump($data);
            $this->assign('data',$data);
            $this->display();
        } 

        // If the uploaded file is not empty , Jump to _upload methods 
        public function upload(){        
            // If it's not empty 
            if(!empty($_FILES))
            {
                $this->_upload();
            }

        }

6. If the submission is not NULL, skip to the _upload method, which implements the image uploading function


<?php
    class ImageAction extends Action{        

        /**
         *  create index  Entry method 
         */
        public function index(){
            $image=M('Image');                        
            $data=$image->order('create_time desc')->find();    // Get the last uploaded image 

            var_dump($data);
            $this->assign('data',$data);
            $this->display();
        } 

        
        // If the uploaded file is not empty , Jump to _upload methods 
        public function upload(){        
            // If it's not empty 
            if(!empty($_FILES))
            {
                $this->_upload();
            }

        }

        
        /***
         *  Realize picture uploading 
         */
        public function _upload(){
            import('@.ORG.UploadFile');
            // Import the upload class 
            $upload = new UploadFile();
            // Set the upload file size 
            $upload->maxSize            = 3292200;
            // Set the upload file type 
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            // Set the attachment upload directory 
            $upload->savePath           = './Uploads/';
            // Setup needs to generate thumbnails, only for image files 
            $upload->thumb              = true;
            //  Sets the path to the reference image library package 
            $upload->imageClassPath     = '@.ORG.Image';
            // Sets the file suffix that you want to generate thumbnails 
            $upload->thumbPrefix        = 'm_,s_';  // production 2 A thumbnail 
            // Sets the maximum width of the thumbnail 
            $upload->thumbMaxWidth      = '400,100';
            // Sets the maximum height of the thumbnail 
            $upload->thumbMaxHeight     = '400,100';
            // Set the rules for uploading files 
            $upload->saveRule           = 'uniqid';
            // Delete the original 
            $upload->thumbRemoveOrigin  = true;

            
            // If the upload is not successful 
            if (!$upload->upload()) 
            {
                // Catch upload exceptions 
                $this->error($upload->getErrorMsg());
            } 
            else 
            {
                // Got successfully uploaded file information 
                $uploadList = $upload->getUploadFileInfo();

                
                // Import picture class 
                import('@.ORG.Image');                

                // to m_ Add watermark to thumbnail , Image::water(' Original file path ',' Watermark image address ')
                Image::water($uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');

                // The image name is assigned to   field image
                $_POST['image'] = $uploadList[0]['savename'];
            }
            $model  = M('image');
            // Save the current data object 
            $data['image']          = $_POST['image'];
            $data['create_time']    = NOW_TIME;
            $list   = $model->add($data);
            if ($list !== false) 
            {
                $this->success(' Upload the picture successfully! ');
            } 
            else 
            {
                $this->error(' Image upload failed !');
            }
        }        
    }
?>

Upload successfully generated two thumbnails

To be clear:

ThinkPHP comes with picture uploading class (UploadFile.class.php) and picture model class (Image.class.php), to the full version of ThinkPHP package only have.

If not, you need to create a folder in ES56en (ES57en), then go to the official website to download the extension pack and put the two files in the ES58en folder.

Mine is case two


Related articles: