如何在cakephp中的数据库中插入图像名称?

时间:2014-05-01 12:53:36

标签: cakephp insert save

到目前为止,我已经实施了以下内容。

我面临的问题是我无法更新文件名,因此我收到错误,导致文件无法上传。

控制器:

public function add(){ 
    if (!empty($this->data)) {  
        if (!empty($this->data['Note'])){  
            $filename = basename($this->data['Note']['note_image']['name']); 
            move_uploaded_file($this->data['Note']['note_image']['tmp_name'],WWW_ROOT . 'files' . DS . $filename); 

            if($this->Note->save($this->data['Note'])){  
                $this->Session->setFlash('The note has been saved');
                $this->redirect(array('action' => 'add'));
            }           
        }  
    }
}

查看:

<?php
echo $this->Form->create('Note', array('type' => 'file'));
echo $this->Form->input('note_title');
echo $this->Form->input('note_desc');
echo $this->Form->input('note_image', array('type' => 'file'));
echo $this->Form->end('Add');
?>

我认为保存功能不存在。有没有办法做到这一点。

1 个答案:

答案 0 :(得分:0)

控制器代码应该是这样的:

public function add(){ 
        if ($this->request->is('post') || $this->request->is('put')) {  
            $file = $this->request->data['Note']['note_image']; 
            if($file['error'] === UPLOAD_ERR_OK)
            {
                $filename = $file['name']; 
                if(move_uploaded_file($file['tmp_name'],WWW_ROOT . 'files' . DS . $filename))
                {
                    $this->request->data['Note']['note_image'] = $filename;
                    if($this->Note->save($this->request->data)){  
                        $this->Session->setFlash('The note has been saved');
                        $this->redirect(array('action' => 'add'));
                    }
                }
            }
            else
            {
                $this->Session->setFlash('ERROR');
                $this->redirect(array('action' => 'add'));
            }              
        }  
    }

查看应该是这样的:

<?php
echo $this->Session->flash();
echo $this->Form->create('Note', array('enctype'=>'multipart/form-data'));
echo $this->Form->input('note_title');
echo $this->Form->input('note_desc');
echo $this->Form->input('note_image', array('type' => 'file'));
echo $this->Form->end('Add');
?>