file upload in cakephp 2.3

前端 未结 4 1680
庸人自扰
庸人自扰 2020-12-18 01:11

I\'m new in cakephp and i\'m trying to create a simple file upload with cakephp 2.3 here is my controller

public function add() {
    if ($this->request-&         


        
4条回答
  •  长情又很酷
    2020-12-18 01:43

    Just incase anyone is searching for it again. Here's my code (tested & used on Cakephp 2.5.5). It is based on http://www.templemantwells.com.au/article/website-development/cakephp-image-uploading-with-database & http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file

    View file (*.ctp)

        Form->create('Image', array('type' => 'file'));
    ?>
    
    
        
    Form->input('Image.submittedfile', array( 'between' => '
    ', 'type' => 'file', 'label' => false )); // echo $this->Form->file('Image.submittedfile'); ?>
    Form->end(__('Send My Image')); ?>

    Controller function (*.php)

        public function uploadPromotion() {
    
        // Custom
        $folderToSaveFiles = WWW_ROOT . 'img/YOUR_IMAGE_FOLDER/' ;
    
    
    
    
        if (!$this->request->is('post')) return;        // Not a POST data!
    
    
        if(!empty($this->request->data))
        {
            //Check if image has been uploaded
            if(!empty($this->request->data['Image']['submittedfile']))
            {
                    $file = $this->request->data['Image']['submittedfile']; //put the data into a var for easy use
    
                    debug( $file );
    
                    $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
    
                    //only process if the extension is valid
                    if(in_array($ext, $arr_ext))
                    {
    
    
                        //do the actual uploading of the file. First arg is the tmp name, second arg is 
                        //where we are putting it
                        $newFilename = $file['name']; // edit/add here as you like your new filename to be.
                        $result = move_uploaded_file( $file['tmp_name'], $folderToSaveFiles . $newFilename );
    
                        debug( $result );
    
                        //prepare the filename for database entry (optional)
                        //$this->data['Image']['image'] = $file['name'];
                    }
            }
    
            //now do the save (optional)
            //if($this->Image->save($this->data)) {...} else {...}
        }
    
    
    
    
    }
    

提交回复
热议问题