MeioUpload Behavior – An improved File Upload Behavior for CakePHP
MeioUpload Behavior is an improved File Upload Behavior for the CakePHP framework. It’s based on the Digital Spaghetti’s Upload Behavior.
Juan Basso created a project hosted at github. I am unable to keep working on this behavior an he is making some updates to the code. I think github is a great tool because you can simply fork the project and make your own changes. Go check his work: http://github.com/jrbasso/MeioUpload/tree/master
Download
MeioUploadBehavior version 1.0.1
Related Articles
- Documentation translated to French
- Documentation translated to Ukrainian
- Junnan’s post
- Dave Rupert’s comment about MeioUpload Behavior
Features
- Can be used for any kind of files;
- Accepts custom directory for files to be uploaded;
- Validates the file extension and mime-type due to the behavior configuration;
- Validates the max file size;
- Allow custom validation rules;
- Allow as many thumbnails formats as you want;
- Allow more then one field to be uploadable, with custom options per field;
- Stores the directory, filesize, and mime-type in the database if the table has these fields. Also allows to customize these fields names;
- Allow the use of default files and deleting files without deleting the entire record;
- Delete files when the record is deleted or updated with a new file;
- Also works in the $model->saveAll method.
Usage
- Place the meio_upload.php file in your app/models/behaviors folder;
- If you want to use thumbnails, download Nate’s phpThumb Component and place it in your app/controllers/components folder;
- Insert in your model table a character varying field:
CREATE TABLE `products` ( `id` int(8) unsigned NOT NULL auto_increment, `name` varchar(255) default NULL, `description` text default NULL, `price` double default NULL, `picture` varchar(255) default NULL, `dir` varchar(255) default NULL, `mimetype` varchar(255) NULL, `filesize` int(11) unsigned default NULL, `created` datetime default NULL, `modified` datetime default NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
- Add the MeioUpload in the $actsAs of your model:
var $actsAs = array( 'MeioUpload' => array( 'picture' => array( 'dir' => 'img{DS}{model}{DS}{field}', 'create_directory' => true, 'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/png'), 'allowed_ext' => array('.jpg', '.jpeg', '.png'), 'thumbsizes' => array( 'normal' => array('width'=>200, 'height'=>200), ), 'default' => 'default.jpg', ) ) ); - Use a form file input to the field:
echo $form->input('picture', array('type' => 'file')); - Make sure your form has multipart/form-data enctype:
echo $form->create('Product',array('type' => 'file')); - Make sure the PHP has permission to write in the folder yous specified and the php.ini allow the MAX_FILE_SIZE you specified.
Options
When you apply the MeioUpload Behavior to a Model, you pass an array with your options. Here are the options you can change and it’s defaults.
-
dir
The folder where the uploaded files will be saved. It must be inside the app/webroot directory and defaults to an empty string, what means that it will be the app/webroot itself. If you specify some path, then it will be app/webroot/the_path_you/specified. In this option you may use the {DS} pattern, what will be converted to ‘/’ in UNIX systems and to ‘\’ in Windows systems. -
allowed_mime
This option specifies the allowed mime-types for the files. It defaults to an empty array. What means that every mime-type will be accepted. But if you specify an array with the mime-types allowed, only files of these mime-types will be accepted.var $actsAs = array( 'picture' => array( 'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/png') ) );The code above says that the picture field will be a file uploaded, and it allows ‘image/jpeg’, ‘image/pjpeg’ and ‘image/png’ mime-types. -
allowed_ext
This option specifies the allowed file extensions. It defaults to an empty array. What means that every extension will be accepted. But if you specify an array with the extensions allowed, only files with these extensions will be accepted.var $actsAs = array( 'picture' => array( 'allowed_ext' => array('.jpg', '.jpeg', '.png') ) );The code above says that the picture field will be a file uploaded, and it allows ‘.jpg’, ‘.jpeg’ and ‘.png’ extensions. -
create_directory
If you want to create the directory specified in the dir option if it don’t exists, then set this option to true. It already defaults to true, but you can set it to false. -
max_size
The max file size allowed in the upload. Be sure it’s lower then the php.ini configuration. You can set a numeric value of bytes, or set it in other unit like ‘8 Kb’, only ‘kb’, ‘mb’, ‘gb’ and ‘tb’ units are allowed and it’s not case-sensitive. It defaults to 2 Mb.var $actsAs = array( 'picture' => array( 'max_size' => '4 Mb' ) ); -
default
If you have a file that you want to use if the field is left blank, like a default picture for users who don’t have one, set this option to the name of this file. Make sure it is inside the folder specified in the ‘dir’ option.var $actsAs = array( 'picture' => array( 'default' => 'default.jpg' ) ); -
fields
With this option you can customize the field inside your model table, where the data will be saved. The filename is the key of the options array, and you can setup fields to store the filesize, mime-type and directory. It defaults to ‘filesize’, ‘mimetype’ and ‘dir’ respectively, but you can customize with an array:var $actsAs = array( 'picture' => array( 'fields' => array( 'filesize' => 'picture_filesize', 'mimetype' => '{field}_mimetype', 'dir' => 'pictures_folder' ) ) );The code above says that your filesize, mimetype and dir fields will be ‘picture_filesize’, ‘picture_mimetype’ and ‘picture_folder’ respectively. And the filename field will be pictures. You may notice that in mimetype case, i used the constant {field} that will be replaced with the field name(picture in this case).
Validations
The behavior automatically include some validations to your field. Here they are:
- FieldName Checks if the field has been setup to be and uploadable.
- Dir Checks if the directory exists or if it can be created. This validation depends on the option ‘create_directory’.
- Empty Checks if the filename is not empty. It defaults to be used only on create.
- UploadError Checks if ocurred erros in the upload.
- MaxSize Checks if the file isn’t bigger then the max file size option.
- InvalidMime Checks if the file is of an allowed mime-type.
- InvalidExt Checks if the file has an allowed extension.
You can overwrite any of the parameters of these default validation rules. Directly in the model $validate var:
var $validate = array(
'picture' => array(
'Empty' => array(
'check' => false
),
'InvalidExt => array(
'message' => 'This file extension isn't allowed.'
)
)
);
In the code above, i changed the message for the ‘InvalidExt’ default validation. You can also disable any of the default validations by setting the ‘check’ atribute fo false as is shown in the example above for the ‘Empty’ default validation. You can change any of the other parameters of the built-in cake validation:
var $validate = array(
'picture' => array(
'Empty' => array(
'rule' => array('YourDefaultValidation'),
'on' => 'update',
'required' => true
),
)
);
You can also change the validation rule for one you have created. But use this functionality carefully.
Setting up file removing
If you send a form data with as field named data[Model][field][remove] not empty, then the behavior will automatically delete the file associated with the record and set it’s value to the default, if it is set, or to empty. To achieve this you can add a checkbox to your form:
echo $form->input('Product.picture.remove', array('type' => 'checkbox'));


February 11th, 2009 at 12:56
The MeioUpload don’t support renaming the file. It simply renames files that have the same name.
February 11th, 2009 at 20:35
@CorneyWalls
Thumbsizes with ‘normal’ as key will be the size of the original uploaded image. So, you have to define a key diferent from ‘normal’.
February 15th, 2009 at 22:46
I’m just beginning to learn my way around cakePHP, and have run into difficulty getting this behavior to work. I’m sure that I’m just doing something wrong, but haven’t been able to figure out.
I’ve got a simple cakePHP app based on 1.2.1.8004 stable. I have a “Teachers” model, to which I’m trying to attach an image file. Right now, “picture” is an attribute of the Teachers model; once I’ve gotten the behavior working, I’ll worry about moving the attachment over to a separate associated model.
I’ve downloaded meio_upload.php, and placed it in /app/models/behaviors.
models/teacher.php (snippet):
var $actsAs = array( // models/behaviors/meio_upload.php ‘MeioUpload’ => array( ‘picture’ => array( ‘dir’ => ‘files{DS}uploads{DS}{model}’, ‘create_directory’ => true, ‘allowed_mime’ => array(‘image/jpeg’, ‘image/pjpeg’, ‘image/png’), ‘allowed_ext’ => array(‘.jpg’, ‘.jpeg’, ‘.png’), ) ) );
views/teachers/admin_add.thtml:
create(‘Teacher’,array(‘type’ => ‘file’)); ?>
input(‘name’); echo $form->input(‘picture’, array(‘type’ => ‘file’)); ?>
end(‘Add Teacher’); ?>
When I post the form, I get the following:
Notice (8): Array to string conversion [CORE/cake/libs/model/datasources/dbo_source.php, line 571]
Warning (512): SQL Error: 1054: Unknown column ‘Array’ in ‘field list’ [CORE/cake/libs/model/datasources/dbo_source.php, line 514]
The posted image’s entire metadata array is being fed to the insert statement, rather than just the image’s filename. I presume this means I haven’t properly installed or initialized meio_upload.php? The notice given (regarding array to string conversion) sounds very relevant to this problem, but I’m not sure what that notice is actually telling me. The line it references is part of the create() function in “The ‘C’ in CRUD”:
$query = array( ‘table’ => $this->fullTableName($model), ‘fields’ => join(‘, ‘, $fieldInsert), ‘values’ => join(‘, ‘, $valueInsert) <– This line );
http://www.meiocodigo.com/projects/meioupload/#comment-6214 appears to be having the same issue, although I didn’t see a reply to his comment.
If anybody has any suggestions on how I might go about troubleshooting this further, or spots the obvious thing I am no doubt missing, I would very much appreciate your comments.
Thank you for your time.
February 16th, 2009 at 13:19
@sutehi Why don’t you use the default $this->Teacher->save($this->data). Looking at your code, it seems like you are trying to create the insert query “by hand” without using the CakePHP database abstraction.
February 17th, 2009 at 13:21
@vbmendes Thank you for the reply. I think we might have a miscommunication. When you say it looks like I am trying to create the insert query by hand, are you referring to the bit of code that I quoted from CORE/cake/libs/model/datasources/dbo_source.php? This is code which ships with cakePHP, not something I’ve written myself. I just included it, because the notice message I received referenced that bit as being related to the problem.
My teachers_controller.php does in fact all ready use $this->Teacher->save($this->data) to save the Teacher object.
February 17th, 2009 at 19:19
Hey Vinicius, this is a great plugin. It has saved me a ton of development time and works better than my past implementations.
However, I did run into a minor a problem while employing MeioUpload. While I did eventually find the solution, it’s not completely obvious, so I thought I’d post it here to save others some time.
Basically, I wanted the “picture.remove” checkbox to be unchecked by default so that when the user won’t accidentally delete an uploaded picture while editing other fields. But since ‘picture’ is never empty in this situation, Cake’s Form Helper automatically enabled the ‘checked’ attribute by default.
Initially, I tried to set the ‘checked’ attribute to “unchecked” like so:
$form->input(‘picture.remove’, array(‘type’ => ‘checkbox’, ‘checked’ => ‘unchecked’));
But that did not work. Neither did setting it to “false” or “no.” Eventually, I came upon the embarrassingly simple solution of simply setting the ‘value’ attribute to an empty string:
$form->input(‘picture.remove’, array(‘type’ => ‘checkbox’, ‘value’ => ”));
So maybe that will save others a little time. If this solution seems obvious, and I’m just dumb, then please ignore or delete this comment.
February 24th, 2009 at 18:41
@sutehi; I’m also bumping into the problem of the Array in the field list. It looks like the beforeSave function (line 596) in the behavior is not executed. On line 652-655 the model data should be updated, but this isn’t happening. Could you please check whether the beforeSave function is executed in your code? Meanwhile I’ll see whether I can fix the problem. Thank you…
February 25th, 2009 at 14:24
@Sytze Loor: Wich PHP version are you using? a recommend PHP 5.
February 25th, 2009 at 16:29
I’m using PHP5 (latest XAMP-release) with Cake 1.2.1.8004 Stable. I’m using the following configuration for the behavior: var $actAs = array( ‘MeioUpload’ => array( ‘file’ => array( ‘dir’ => ‘uploads’, ‘create_directory’ => true, ‘fields’ => array( ‘filesize’ => ‘filesize’, ‘mimetype’ => ‘filetype’, ‘dir’ => ‘directory’ ) ) ) ); Any help is welcome!
March 5th, 2009 at 14:30
Estou tendo um problema na hora de fazer a edição de um cadastro, ele altera o cadastro certinho, e também faz o upload da nova imagem, porem não elimina do FTP a imagem antiga. Ahh e não apresenta erro algum. Se puder me ajudar, agradeço desde já.