在控制器中添加功能
public function add() {
$this->Model->create();
if ($this->request->is('post')) {
if(!empty($this->data['Model']['image']['name']))
{
$file=$this->data['Model']['image'];
$ary_ext=array('jpg','jpeg','gif','png');
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . $file['name']);
$this->request->data['Model']['image'] = $file['name'];
}
}
if ($this->Model->save($this->request->data))
{
$this->Session->setFlash('Your record has been saved.');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('Unable to add your record.');
}
}
}
File control in add.ctp file
echo $this->Form->input('image',array('type'=>'file'));
you can define constant in index.php file like below
/**
* Get Cake's root directory
*/
define('APP_DIR', 'app');
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__));
define('WEBROOT_DIR', 'webroot');
define('WWW_ROOT', ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS);