CakePHP: Upload File

The Model

<?php

App::uses('AppModel', 'Model');

class Picture extends AppModel {
	public $useTable = 'picture';
	public $primaryKey = 'id';
	public $name = 'Picture';
	public $order = 'Picture.id ASC';

	protected $_displayFields = array(
		'id',
		'name',
		'link',
	);
}
?>

The Database

CREATE TABLE `picture` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `link` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The View

<?php
	echo $this->Form->create('Upload',array(
		'enctype' => 'multipart/form-data',
		'url' => array(
			'controller' => 'upload', 
			'action' => 'index'
		)
	));
	echo $this->Form->file('file');
	echo $this->Form->end(array(
		'label' => 'Submit',
		'class' => 'btn btn-success'
	));
?>

The Controller

<?php

App::uses('AppController', 'Controller');

class UploadController extends AppController { 
	public function index() {
                // in this example, we're trying to accept gif,jpeg and png

                $image = $this->request->data['Upload']['file'];

                $imageTypes = array("image/gif", "image/jpeg", "image/png");

                $uploadFolder = "img" . DS . "photos" . DS;

                $uploadPath = WWW_ROOT . $uploadFolder;

                $id = null;

                if(!empty($image['name']))
                {
                        $ext = substr(strtolower(strrchr($image['name'], '.')), 1); //get the extension

                        if(in_array($image['type'], $imageTypes))
                        {
                                $date = date_create();
                                $rand = rand(100000,999999);
                                $link = 'pic_' . date_format($date, 'U') . '_' . $rand . '.' . $ext;

                                move_uploaded_file($image['tmp_name'], $uploadPath . $link);

                                $this->Picture->create();
                                $this->Picture->set(array('name' => $image['name'], 'link' => $link));
                                $this->Picture->save();
                                $id = $this->Picture->id;
                                $this->Session->setFlash('Picture uploaded!');
                        }
                        else
                        {
                                $this->Session->setFlash('Only files with extension .gif, .png and .jpeg are allowed to be upload.');
                        }
                }

	}
}
?>

Leave a comment