Header menu


Saturday, 21 September 2013

Upload file in cakephp using move_uploaded_file function


Easiest way to upload file in cakephp is by using move_uploded_file function.
But it beneficial when you have to put file uploader at few place. If you need
to place large number of form which upload file then use component method otherwise
this is easier and much faster way.

I need one multipart form which can select file to upload i have  created one in
index.ctp and rest of the work will be done by index function in controller.

This is my controller file

class ContactsController extends ContactManagerAppController {
    public $uses = array('ContactManager.Contact');

    public function index() {
            $filePath = "./img/".$this->request->data['Contact']['image_file']['name']; 
            if(move_uploaded_file($this->request->data['Contact']['image_file']['tmp_name'], $filePath)){
            echo "File uploaded Successfully";

This is view for my Controller

    echo $this->Form->create('Contact', array('enctype' => 'multipart/form-data', 'class'=>'form-horizontal'));
    <label class="control-label" for="inputError">Image</label>
    echo $this->Form->file('image_file');
    echo $this->Form->submit(__('Submit') , array('class'=>'btn btn-primary'));