CakePHP3-上传图像文件

2022-07-12 00:00:00 php cakephp-3.0

我在cakephp3方面是新手。我有一个Employee表,我想保存一个图像路径。 下面是我在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() ?>

我希望在我的EmployeesController.php中使用Upload函数。我曾尝试使用php move_ploaded_file保存它,但它不起作用。下面是控制器。

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']);
}

解决方案

在您的视图中尝试此结构

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

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

控制器

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']);
}

相关文章