CakePHP3 - Upload image file

强颜欢笑 提交于 2019-12-13 05:54:07

问题


I am new in cakephp3. I have an Employee Table and I want to save an image path. Below is my form in add.ctp

<?php echo $this->Form->create($employee, ['enctype' => 'multipart/form-data']); ?>
<fieldset>
    <legend><?= __('Add Employee') ?></legend>
    <?php
        echo $this->Form->input('image_path', ['type' => 'file']);
        echo $this->Form->input('first_name');
        echo $this->Form->input('last_name');

        echo $this->Form->input('birthday', 
            array(
                'type' => 'date',
                'label' => 'Birthday',
                'dateFormat' => 'MDY',
                'empty' => array(
                    'month' => 'Month',
                    'day'   => 'Day',
                    'year'  => 'Year'
                ),
                'minYear' => date('Y')-130,
                'maxYear' => date('Y'),
                'options' => array('1','2')
            )
        );

        echo $this->Form->input('address');
        echo $this->Form->input('contact');

        echo $this->Form->input('date_hired', 
            array(
                'type' => 'date',
                'label' => 'Date Hired',
                'dateFormat' => 'MDY',
                'empty' => array(
                    'month' => 'Month',
                    'day'   => 'Day',
                    'year'  => 'Year'
                ),
                'minYear' => date('Y')-130,
                'maxYear' => date('Y'),
                'options' => array('1','2')
            )
        );

        $status = array(
            "employed" => "Employed",
            "unemployed" => "Unemployed"
        );

        echo $this->Form->input('status', array('label'=>'Status', 'type'=>'select', 'options'=>$status));
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

I want to make the upload function work in my EmployeesController.php. I have tried to save it using php move_uploaded_file but it is not working. Below is the controller.

public function add()
{
    $employee = $this->Employees->newEntity();

    if ($this->request->is('post')) {
        $employee = $this->Employees->patchEntity($employee, $this->request->data);

        $employee->user_id = $this->Auth->user('id');
        if ($this->Employees->save($employee)) {
            $this->Flash->success(__('The employee has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The employee could not be saved. Please, try again.'));
        } 

        if(!empty($this->data))
        {
            //Check if image has been uploaded
            if(!empty($this->data['employees']['image_path']['name']))
            {
                $file = $this->data['employees']['image_path']; //put the data into a var for easy use

                $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
                    move_uploaded_file($file['tmp_name'], WWW_ROOT . 'CakePHP/app/webroot/img/' . $file['name']);

                    //prepare the filename for database entry
                    $this->data['employees']['product_image'] = $file['name'];
                }
            }

            //now do the save
            $this->Employees->save($this->data) ;
        }

    }

    $users = $this->Employees->Users->find('list', ['limit' => 200]);
    $this->set(compact('employee', 'users'));
    $this->set('_serialize', ['employee']);
}

回答1:


Try this structure in your View

<?= $this -> Form -> create($employee, ['type' => 'file']) ?>
    ...
    <?= $this -> Form -> input('image_path', ['type' => 'file', 'label' => __('Select Image')]) ?>

    <?= $this -> Form -> input('first_name') ?>
    ... 
<?= $this -> Form -> end() ?>

Controller

public function add()
{
    $employee = $this->Employees->newEntity();

    if ($this->request->is('post')) 
    {

        $employee = $this->Employees->patchEntity($employee, $this->request->data);

        $employee['user_id'] = $this->Auth->user('id');

        //Check if image has been uploaded
        if(!empty($this->data['employees']['image_path']['name']))
        {
            $file = $this->data['employees']['image_path']; //put the data into a var for easy use

            $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))
            {
                //name image to saved in database
                $employee['product_image'] = $file['name'];

                $dir = WWW_ROOT . 'img' . DS; //<!-- app/webroot/img/

                //do the actual uploading of the file. First arg is the tmp name, second arg is
                //where we are putting it
               if(!move_uploaded_file($file['tmp_name'], $dir . $file['name'])) 
               {
                   $this -> Flash -> error(__('Image could not be saved. Please, try again.'));

                   return $this->redirect(['action' => 'index']);
                }

            }
        }

        //now do the save
        if ($this->Employees->save($employee)) 
        {
            $this->Flash->success(__('The employee has been saved.'));

            return $this->redirect(['action' => 'index']);

        } else {

            $this->Flash->error(__('The employee could not be saved. Please, try again.'));
        } 
    }

    $users = $this->Employees->Users->find('list', ['limit' => 200]);

    $this->set(compact('employee', 'users'));
    $this->set('_serialize', ['employee']);
}


来源:https://stackoverflow.com/questions/38049805/cakephp3-upload-image-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!