CakePHP3中的图像上传和数据保存冲突

时间:2016-11-06 18:17:39

标签: cakephp cakephp-3.0

我正在尝试在我的cakephp 3.x应用程序中上传图片。当没有上传图像时,其他数据保存得很好但是由于文件上传集成,图像上传功能正常工作但其他数据没有保存。下面是示例代码。请看,因为我认为可能只有一些小问题,我找不到。以下是控制器中添加操作的代码:

    $team_member = $this->TeamMembers->newEntity();
    if ($this->request->is('post')) {
        if (!empty($this->request->data['photo']['name'])) {
            $photo = $this->request->data['photo'];

            $ext = substr(strtolower(strrchr($photo['name'], '.')), 1); //get the extension
            $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
            $setNewFileName = time() . "_" . rand(000000, 999999);

            //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($photo['tmp_name'], WWW_ROOT . '/uploads/' . $setNewFileName . '.' . $ext);
                //prepare the filename for database entry 
                $imageFileName = $setNewFileName . '.' . $ext;
            }
        }

        $team_member = $this->TeamMembers->patchEntity($team_member, $this->request->data);
        if (!empty($this->request->data['photo']['name'])) {
            $team_member->photo = $imageFileName;
        }
        if ($this->TeamMembers->save($team_member)) {
            $this->Flash->success(__('Saved Successfully.'));
            return $this->redirect([
                    'action' => 'index'
            ]);
        }
        $this->Flash->error(__('Failed to save. Try Again.'));
    }
    $this->set('team_member', $team_member);

这是add.ctp文件:

echo $this->Form->create($team_member, ['enctype' => 'multipart/form-data']);
echo $this->Form->input('name');
echo $this->Form->input('photo', array('type' => 'file'));
echo $this->Form->input('excerpt');
echo $this->Form->input('content');
echo $this->Form->button('Save', ['class' => 'btn']);
echo $this->Form->end();

请注意,之前我没有为文件上传编写任何代码时工作正常。而且,CakePHP版本是3.x

TIA

1 个答案:

答案 0 :(得分:-2)

我刚才得到了答案。我不知道为什么它起作用,因为逻辑上这是不正确的,但它现在工作正常。 我刚刚在add.ctp文件中替换了这行代码

echo $this->Form->create($team_member, ['enctype' => 'multipart/form-data']);

echo $this->Form->create($team_member);

无论如何,现在工作正常。但是,如果您能澄清原因,那么因为每个具有文件上传的表单都应该将enctype作为multipart / form-data。