Upload image in cakephp -
i want have in function (add) file upload process in cake application. have tried various tutorial across web bur reach solution problem. new cake , dont want reinvent wheel want learn based on have implemented far. grateful help.
add.ctp
<?php echo $this->form->create('movie'); ?> <?php echo __('add movie'); ?> <?php echo $this->form->hidden('movie_id'); echo $this->form->input('title'); echo $this->form->input('date', array( 'type' => 'date', 'label' => 'date', 'empty' => false, 'dateformat' => 'dmy', 'minyear'=>'1990', 'maxyear'=>date('y'), )); echo $this->form->input('description'); echo $this->form->input('file', array('type' => 'file'));?> <?php echo $this->form->end(__('submit')); ?>
the controller
public function add() { if ($this->request->is('post')) { $this->movie->create(); } if ($this->movie->save($this->request->data)) { $this->session->setflash(__('the movie has been created')); $this->redirect (array('action'=>'index')); } }
table structure table movies
create table if not exists `movies` ( `id` int(11) not null auto_increment, `movie_id` int(11) not null, `title` varchar(100) not null, `file` varchar(200) not null, `date` date not null, `description` text not null, primary key (`id`), unique key `movie_id` (`movie_id`), key `id` (`id`) ) engine=innodb default charset=latin1 auto_increment=2 ;
create model located @ /app/model/movies.php
<?php class movie extends appmodel { } ?>
create controller in app/controller/movies.php
<?php class moviescontroller extends appcontroller { public function add() { if ($this->request->is('post')) { $maxid = $this->movie->find('first', array( 'order' => 'movie_id desc', 'fields' => array('movie.movie_id') )); $maxid = (isset($maxid['movie']['movie_id'])? $maxid['movie']['movie_id'] : 0); $this->request->data['movie']['movie_id'] = $maxid+1; $foldertosavefiles = www_root . 'img/uploads/' ; if(!empty($this->request->data['movie']['file'])) { $file = $this->request->data['movie']['file']; $ext = substr(strtolower(strrchr($file['name'], '.')), 1); $arr_ext = array('jpg', 'jpeg', 'gif','png'); if(in_array($ext, $arr_ext)) { $newfilename = $this->request->data['movie']['title'].'.'.$ext; $result = move_uploaded_file( $file['tmp_name'], $foldertosavefiles . $newfilename ); $this->request->data['movie']['file'] = $newfilename; $this->movie->save($this->request->data); //debug($this->request->data); } } } }
note : create directory in app/webroot/img/uploads/ & upload directory must write permission.
Comments
Post a Comment