Cake File Handler

modified file handler component for file uploads using CakePHP

After discovering Chris Partridge's excellent File Handler component, I decided to integrate it into one of my applications. On the surface it worked great. Unfortunately, when I tried to use a database to store the information, things started to go awry. Now, I can't be sure if there were actual bugs in the code (although there were some typos) or I simply misunderstood how to fully use it correctly (I'm still learning all the ins and outs of cake), but since I also wanted a couple of features that weren't present, I decided to rewrite most of the component.

I moved the error checking out of the main upload method and added mutator methods for a few of the settings. Coming from a java background, I prefer my reusable objects more black-boxed with as little code-diving as possible when using them in separate applications.

The main features I added were multiple uploads and the ability to require zero or more files.

Let's Get Started

But before we start, you can download all the necessary code with the component below.

Model

Since this is based on Chris Partridge's FileHandler, you have the option to use a database to store upload information or get an array that you can handle however you wish. The database table contains the following:
CREATE TABLE `file_uploads` (
    `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `file_name` varchar(50) NOT NULL DEFAULT '',
    `mime_type` varchar(32) NOT NULL,
    `file_size` varchar(50) NOT NULL,
    `subdir` varchar(25) NOT NULL,
    `extra_field` varchar(50),
    `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
    `modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
    PRIMARY KEY(`id`)
);  
Notice the extra_field - you can add any extra fields you want to the table, but make sure the initial fields are present.
Be careful with additional field names, as the component uses array_merge, which will overwrite existing names

View

Whether you're uploading single or multiple files, be sure to set an array-based input:
<input type="file" name="userfile[]"/>  

Controller

Finally, you want to include the component:

var $components = array('FileHandler');  

In your controller action, you can set up the component for your needs:

$this->FileHandler->setDebugLevel(1);
$this->FileHandler->setRequired(0);
$this->FileHandler->setHandlerType('db');
$this->FileHandler->setDbModel('FileUpload');
$this->FileHandler->addDbFields($dbFields);  
That last little bit shows how to append extra database fields to the file_uploads table. $dbFields would be array(field => value);

Finally, you can process the file upload:

if ($this->FileHandler->upload('userfile', $uploadDir)) {
    echo 'upload succeeded';
} else {
    echo 'upload failed';
}  

Download

The following zip file contains the component and necessary code to run an example. rf_filehandler.zip
BACK TO TOP