-
Notifications
You must be signed in to change notification settings - Fork 59
Usage
We will pretend to add this to the Image
Model, so to begin, here is a barebones table for our model:
CREATE TABLE `images` (
`id` int(8) unsigned NOT NULL auto_increment,
`image` varchar(255) default NULL,
`created` datetime default NULL,
`modified` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
You’ll note that our image
field will be used to hold the image filename. Here is the sample model for this table:
<?php
class Image extends AppModel {
var $name = 'Image';
var $actsAs = array(
'MeioUpload.MeioUpload' => array('image')
);
}
?>
Because this is a Behavior, we do not need to do anything special in our Controllers. Remember, data manipulation occurs in the model, hence the Behavior :)
In order to save our data correctly, we have to place the right input fields in the form. Here is a sample form:
<?php echo $form->create('Image', array('type' => 'file')); ?>
<?php echo $form->input('Image.image', array('type' => 'file')); ?>
<?php echo $form->end('Submit'); ?>
You’ll notice that both the $form->create()
and $form->input()
have the type
parameter set to file
. This will tell the FormHelper to correctly output a Form that will be multipart/form-data encoded with a form input field. Neat.
If you try to upload now and you are on your own machine, not a development server or similar, it should work. But if it does not, or you are on a development server, here is what is wrong
- CakePHP tries to save the data
- MeioUpload is called in the
Model::beforeSave()
method - MeioUpload tries to upload your images to the
app/webroot/uploads/image/image
directory - OOPS! You forgot to both create that directory and also set the permissions
To solve this issue, simply create the directory and allow the server to save data to the folder. something like chmod -R 755 uploads
in your webroot directory should solve this issue.