I'm new in cakephp and i'm trying to create a simple file upload with cakephp 2.3 here is my controller
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
$filename = WWW_ROOT. DS . 'documents'.DS.$this->data['posts']['doc_file']['name'];
move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
and my add.ctp
echo $this->Form->create('Post');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('keywords');
echo $this->Form->create('Post', array( 'type' => 'file'));
echo $this->Form->input('doc_file',array( 'type' => 'file'));
echo $this->Form->end('Submit')
it saves firstname, lastname, keywords, and the name of the file in DB , but the file which i want to save in app/webroot/documents is not saving , can anyone help ? Thanks
Update
thaJeztah i did as u said but it gives some errors here is controller if i'm not wrong
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
$filename = WWW_ROOT. DS . 'documents'.DS.$this->request->data['Post']['doc_file']['name'];
move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
and my add.ctp
echo $this->Form->create('Post', array( 'type' => 'file'));
echo $this->Form->input('firstname'); echo $this->Form->input('lastname');
echo $this->Form->input('keywords');
echo $this->Form->input('doc_file',array( 'type' => 'file'));
echo $this->Form->end('Submit')
and the errors are
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1005]
Database Error Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'field list'
SQL Query: INSERT INTO first.posts (firstname, lastname, keywords, doc_file) VALUES ('dfg', 'cbhcfb', 'dfdbd', Array)
and Victor i did your version too , it doesnt work too .
$this->data['posts']['doc_file']['tmp_name']
, which should be$this->data['Post']['doc_file']['tmp_name']
. However, the problem you're seeing is caused because you're trying to use$this->data['Post']['doc_file']
as value for the 'doc_file' field in your database, but because this is an array, this won't work directly. You'll have to change that data and only use the file-name for your database. I'll try to add an example – Breechblock