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.

Download

MeioUploadBehavior version 1.0.1

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

  1. Place the meio_upload.php file in your app/models/behaviors folder;
  2. If you want to use thumbnails, download Nate’s phpThumb Component and place it in your app/controllers/components folder;
  3. 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;
    
  4. 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',
    		)
    	)
    );
    
  5. Use a form file input to the field:
    echo $form->input('picture', array('type' => 'file'));
    
  6. Make sure your form has multipart/form-data enctype:
    echo $form->create('Product',array('type' => 'file'));
    
  7. 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.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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'
    	)
    );
    
  6. 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'
    	)
    );
    
  7. 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:

  1. FieldName
    Checks if the field has been setup to be and uploadable.
  2. Dir
    Checks if the directory exists or if it can be created. This validation depends on the option ‘create_directory’.
  3. Empty
    Checks if the filename is not empty. It defaults to be used only on create.
  4. UploadError
    Checks if ocurred erros in the upload.
  5. MaxSize
    Checks if the file isn’t bigger then the max file size option.
  6. InvalidMime
    Checks if the file is of an allowed mime-type.
  7. 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'));

46 Responses to “MeioUpload Behavior - An improved File Upload Behavior for CakePHP”

  1. MeioUpload Behavior 1.0 released! | Meio Código says:

    [...] am glad to show you the MeioUpload Behavior 1.0. An improved Upload Behavior for CakePHP 1.2. It turns file uploads as simple as definig a [...]

  2. Nookie says:

    Is it possible to upload multiple files ?

  3. Vinicius Mendes says:

    Yes, it is possible to upload multiple files. But it is not so transparent. I will post an example of this.

  4. Joey says:

    I’m looking forward to seeing the multiple image demo!

  5. luke says:

    looks good - is it using saveAll the multiple method?

  6. luke says:

    hi Vinicius

    I get an error in upload behaviour - fixName() function throws an error (although upload is working and file is saved).

    $this->__model->data is empty array by the time this is called. (so after a validation ?)

    It makes an error notice

  7. luke says:

    sorry, just been trying it out. Validation doesnt seemt to work and throws an error for use of Empty validation:

    Warning (2): preg_match() expects parameter 2 to be string, array given [CORE/cake/libs/validation.php, line 876]

  8. Vinicius Mendes says:

    Luke,

    I need to know what you made. How is your model? What’s the name of the file you are wanting to upload? You used custom validation rules in your model? It’s very hard to detect an error just with the error message. I will be happy if you answer these questions.

  9. luke says:

    Hi Vinicius - thanks for the reply. No, I used just the validation you had.

    I am going to try with the Product model demo I have found and see if I can get it to work. Should this be compatible with RC3 and RC2 of cake 1.2?

  10. Russell Griffith says:

    Hello, are the fields defined in the ‘fields’ option optional fields? What I mean is the example field given above “`picture` varchar(255) default NULL” sufficient for the file to be uploaded or do I need to have the fields filesize, mimetype and dir in my Model.

    Also, wouldn’t multiple images be handled like this:

    var $actsAs = array(
    ‘MeioUpload’ => array(
    ‘picture1′ => 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’,
    ),
    ‘picture2′ => 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’ => ‘default2.jpg’,
    )
    )
    );

  11. Vinicius Mendes says:

    @luke
    I tested it with RC3, but I think it works OK with RC2.

    @Russel Griffith
    Yes, only the picture field is sufficient, the other ones is available if you want to store these informations in the database. About the multiple upload, it can be this way you said, but in this case, you will limit the amount of files to 2, and you will have two fields in your table to store the path to the files. I think the best way to make multiple uploads is have a model just for uploads and have a row in its table for each uploaded file.

  12. Russell Griffith says:

    Thank you for your quick response and answers. About multiple file uploads, I see what you are saying about having a model just for uploads, but wouldn’t that also necessitate a join (called has_many :through in RoR) that would also necessitate an extra field in the “through” table to help identify what type of image it was?

    The kind of join I’m thinking this would have to be is outlined in this article.

    http://debuggable.com/posts/modeling-relationships-in-cakephp-faking-rails-throughassociation:480f4dd6-b990-485e-abe4-4baccbdd56cb

    Seems to me this is the only way to have multiple images related to back to one model. Would you agree with this?

    Hope this makes sense.

  13. Joey says:

    is there an easy way to make the thumbnails crop the image instead of keeping the proportions and resizing?

  14. Joey says:

    oh, nevermind. i sorted it out. thank you for this! works great!

  15. luke says:

    Hi Vin.

    I have tried again just now with the Product demo files you gave using RC3 and I bake the products_controller. I still get a notice for Notice (8): Undefined index: Product [APP/models/behaviors/meio_upload.php, line 506]

    it is the rename fix function. There is no data any more in the array at this point.

    My model, view and my database are EXACTLY as you have in the demo folder.

    I am thinking it is maybe because I do not use a thumbs component? It does upload the file and so on so I can avoid the notice by turning errors off, but I prefer not to.

    thanks for your help. It’s a nice behaviour alright :)

  16. luke says:

    I can email you the code but how can I show you on here? I dont think it is possible? Can you email me if you want to see the code? Thank you again for your time and work on this.

  17. luke says:

    Hi Vinicius is there a way to disable the validation the behavior does? I will use a custom function I have , which works in a basic way.

    I sent you a zip file yesterday after you mailed me - hope you got it OK!

    thank you for your help on this.
    thanks, Luke

  18. Sergio says:

    Hi,

    great entry! I’m trying to upload images y thumbnails, the image get saved in the specified folder, but it looks like the thumb component is not working. Any idea what am I doing wrong?

    Regards

  19. jarrett says:

    Nice piece of code, very helpful, would it b possible and efficient 2 include this behavior in the app_model.php, if most of your models are using it?. And how would I go about this?

  20. Vinicius Mendes says:

    @Sergio
    Without seeing the code I am unable to say what you are doing wrong. To use thumbnails, you have only to write put the component in components path (/app/controllers/components/) and set it in the model. There is an example of this in the docs. Just one thing: if you set the name of the thumbnail as normal, it will resize the file uploaded to this size and overwrite the uploaded one.

  21. Vinicius Mendes says:

    @jarret
    If your models have the same field to store the uploaded file, you can do this. But I think theres a better solution, using a model to store all the files. For example: File. And make a relationship with all models using PolymrpicBehavior ( http://bakery.cakephp.org/articles/view/polymorphic-behavior )

  22. jarrett says:

    Tx for fast reply, much appreciated. I had a look at your link, but failed epically:-D.
    So I created a file manager model separately, based on your behavior, and added a belongsTo relationship to each model using images.
    And in my controller, before a save, I have,
    $this->City->Filemanager->save($image)
    $this->data['City']['filemanager_id'] = $this->City->Filemanager->getLastInsertID();
    and it works great:-), tx again, and keepit up..jj

  23. Vinicius Mendes says:

    @jarret
    That’s not the best way to do this. I think the City doesn’t belongs to the File. In my point of view, the File belongsTo the City. And the Polymorphic behavior allows this. It’s basic concept is that you have a foreign key attribute, and a model name attribute. So each File will belong to a different model. And to know wich model the File belongs to, you just have to check it’s model name attribule.

    I saw somewhere an example showing how to use the polymorphic behavior with the upload behavior I was based, but I can’t find it anymore.

  24. jarrett says:

    So saving it in a separate model (Filemanager) that handles file uploads and then getting the id and storing it in the model (City) that uses images, not the best way, I see your point, while applying my previous solution through 15 models that all have images. I will spend today on the link you sent me, tx again V…jj

  25. lucas says:

    you say that this requires phpthumb, and in your createthumb function you import the Thumb component. however, your code never seems to actually use the Thumb component or phpthumb. what gives????

  26. Vinicius Mendes says:

    @lucas
    This is a requirement of the behavior I used as base. I think you actually don’t need it. You can try it and tell us the result.

  27. Daniel says:

    Bom Dia Vinicius,
    Como que ue faço pra enviar multiplos arquivos com o teu behavior? no caso vo ter vários campos com o nome de imagem[]. No caso seria um array de várias imagens, como eu trato isso com o Behavior?

    Obrigado.

  28. Gabriel says:

    Hello

    I have the same problen than luke.
    It loads the file but it displays the following message :

    Notice (8): Undefined index: {Model} … in 550
    meiouploadbehavior::fixname() - [internal], line ??
    meiouploadbehavior::fixname() - /homez.40/…/cakephp/app/models/behaviors/meio_upload.php, line 550
    meiouploadbehavior::beforesave() - /homez.40/…/cakephp/app/models/behaviors/meio_upload.php, line 628
    meiouploadbehavior::dispatchmethod() - /homez.40/…/cakephp/cake/libs/model/behavior.php, line 163
    behaviorcollection::trigger() - /homez.40/… /cakephp/cake/libs/model/behavior.php, line 445

    My website runs with CakePHP 1.2.0.7692 RC3

    Thanks for your help

  29. Luke says:

    Hi Gabriel, I never have managed to fix this. I am waiting for a new release to try again and perhaps with another version of cake (latest SVN). I tried with RC2 and RC3. But others do not have the problem so I wonder what causes it.

  30. Gabriel says:

    Hi Luke,

    Thanks for your answer.

    I noticed another problems.
    If I load 2 times the same file, the older version is replaced with the new one (the new one isn’t renamed).
    It failed to create automaticaly a new folder.

    It’s pity because this bahaviour looks great and convenient.

    So do you know another tools for cake to upload files ?

    Gabriel

  31. Russ (rgreenphotodesign) says:

    The site I listed is not the one I’m using this for. But I do have a question. Hope it’s not a stupid one :)

    I have a model called Miscfile and the database contains the basic elements in your example with a couple of custom fields.

    var $actsAs = array(
    ‘MeioUpload’ => array(
    ‘audiofile’ => array(
    ‘dir’ => ‘userfiles{DS}audio’,
    ‘create_directory’ => true,
    ‘allowed_mime’ => array(’audio/wav’),
    ‘allowed_ext’ => array(’.wav’),
    ),

    )
    );

    I can’t seem to get any data to store in the table, the file uploads fine, but nothing in the database.

    here is my action in controller.
    function add()
    {
    $this->Miscfile->saveAll($this->data);
    $this->set(’message’, ‘Your file has been uploaded’);
    $this->render(’audio’);
    }

    View:

    create(’Miscfile’, array(’type’ => ‘file’)); ?>
    input(’audiofile’, array(’type’ => ‘file’)); ?>
    input(’title’); ?>
    end(’Upload File’); ?>

    Again the file uploads fine, but no DB. Feels like I’m missing something super simple or obvious!

  32. faemino says:

    Hi Vinicius, First thanks for this useful behavior.

    When I try to update a model from a form with a “remove” checkbox (set true), the recordset be updated but the file isn’t deleted.

    Dive in your code in the beforeSave method the next code block:

    //if the record is already saved in the database, set the existing file to be removed after the save is sucessfull
    if(!empty($model->data[$model->name][$model->primaryKey])){
    $this->setFileToRemove($fieldName);
    }

    don’t delete the file in edit action.

    For now I’ve put these ugly else:

    } else {
    $this->setFileToRemove($fieldName);
    }

    And edit and file deletion works fine. Another actions like add works too.
    For now, I can’t look better your code and learn about it to see if I’m wrong or to propose a better solution than a else.

    Sorry for my poor english.
    Cheers and thanks
    faemino

  33. gabriel says:

    Hi Luke,

    I found the problem for the following message :

    Notice (8): Undefined index: {Model} … in 550
    meiouploadbehavior::fixname() - [internal], line ??

    I left caracters after “?>” tag in my class or files configuration. Now it’s ok.

    However I have still this problem : If I load 2 times the same file, the older version is replaced with the new one (the new one isn’t renamed).

    See you

    Gabriel

  34. gabriel says:

    Hello,

    What’s happen if I download the same file 2 times (2 rows in the db for one file in the same directoy) and I delete one row in the DB ?

    See you !

  35. Tickão says:

    Olá, sou iniciante no Cake.

    Fiz e refiz os passos e não consegui fazer o upload.

    O sistema está em desenvolvimento no windows, tentei varias vezes mas simplesmente não faz o upload, não grava o campo file no BD e não dá nenhum erro.

    Será que vc poderia me ajudar? Fora os procedimentos acima precisa mais algum outro no controller por exemplo?

  36. Gabriel says:

    I notice you should set variable debug on 0.

    If debbug > 0 you’ll have the following error :

    Notice (8): Undefined index: {Model} … in 550
    meiouploadbehavior::fixname() - [internal], line ??

  37. berger says:

    Hi,
    everything works almost fine with me. Except the redirect after add and delete. For some reasons it gets redirected to the same page (add to add, delete to delete). In the case of delete this results in an infinite loop… any suggestions?

    greetz berger

  38. Sparkybarkalot says:

    I’m having problems getting this to work and I’m wondering if you have a solution. When I hit the submit button for the form, I get this notice and error:
    “Notice (8): Array to string conversion [CORE\cake\libs\model\datasources\dbo_source.php, line 571]”
    and
    “Warning (512): SQL Error: 1054: Unknown column ‘Array’ in ‘field list’ [CORE\cake\libs\model\datasources\dbo_source.php, line 514]”
    I found two recommended solutions elsewhere online, but neither solved my problem. This is in my model:
    var $actsAs = array(
    ‘MeioUpload’ => array(
    ‘picture’ => array(
    ‘dir’ => ‘files{DS}pictures’,
    ‘allowed_mime’ => array(’image/jpeg’, ‘image/pjpeg’, ‘image/png’),
    ‘allowed_ext’ => array(’.jpg’, ‘.jpeg’, ‘.png’),
    ‘default’ => ‘default.jpg’
    )
    )
    );

    This is in my view:
    create(’Painting’, array(’type’ => ‘file’)); ?>

    input(’title’);
    echo $form->input(’location_id’);
    echo $form->input(’size’);
    echo $form->input(’date_moved’);
    echo $form->input(’picture’, array(’type’ => ‘file’));
    ?>

    end(’Submit’);?>

    Any suggestions?

  39. Mohammad Nuaimat says:

    Dear

    how can i specify ‘dir’ config such that it creates a folder for current model and a subfolder for current model record id then place the file inside this subfolder.

    ex:
    Model: Profile
    Id: 12
    Fname: test.jpg

    this should be found in /webroot/files/Profile/12/test.jpg

    anyway ??

  40. John says:

    Hi. First of all I just want to say thanks for making such a useful bit of code available to everyone. I’ve got the behaviour working in a basic way with no problems at all.

    Apologies in advance as this is probably a really obvious question. I wanted to save the field(s) using a habtm relationship.

    Product HABTM Image

    My Models are as follows:

    array(’className’ => ‘Image’,
    ‘joinTable’ => ‘images_products’,
    ‘foreignKey’ => ‘product_id’,
    ‘associationForeignKey’ => ‘image_id’,
    ‘unique’ => true,
    ‘conditions’ => ”,
    ‘fields’ => ”,
    ‘order’ => ”,
    ‘limit’ => ”,
    ‘offset’ => ”,
    ‘finderQuery’ => ”,
    ‘deleteQuery’ => ”,
    ‘insertQuery’ => ”
    )
    );

    }
    ?>

    array(’className’ => ‘Product’,
    ‘joinTable’ => ‘images_products’,
    ‘foreignKey’ => ‘image_id’,
    ‘associationForeignKey’ => ‘product_id’,
    ‘unique’ => true,
    ‘conditions’ => ”,
    ‘fields’ => ”,
    ‘order’ => ”,
    ‘limit’ => ”,
    ‘offset’ => ”,
    ‘finderQuery’ => ”,
    ‘deleteQuery’ => ”,
    ‘insertQuery’ => ”
    )
    );

    /* use the upload compaonent */
    var $actsAs = array(
    ‘MeioUpload’ => array(
    ‘filename’ => 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(
    ’small’ => array(’width’=>100, ‘height’=>100),
    ‘medium’ => array(’width’=>220, ‘height’=>220),
    ‘large’ => array(’width’=>800, ‘height’=>600)
    )
    /*’default’ => ‘default.jpg’,*/
    )
    )
    );

    }
    ?>

    And my view is really simple:

    create(’Product’, array(’type’ => ‘file’));?>

    input(’name’);
    echo $form->input(’live’);
    echo $form->input(’deleted’);
    //echo $form->input(’Image.filename’, array(’type’ => ‘file’));

    ?>

    Filename

    end();?>

    and my view

    data)) {

    //pr($this->data);

    $this->Product->create();
    if ($this->Product->save($this->data)) {
    $this->Session->setFlash(__(’The Product has been saved’, true));
    $this->redirect(array(’action’=>’index’));
    } else {
    $this->Session->setFlash(__(’The Product could not be saved. Please, try again.’, true));
    }
    }
    $images = $this->Product->Image->find(’list’);
    $this->set(compact(’images’));
    }

    I don’t get any error messages, it is just that the image isn’t uploaded and no data is saved to the images table.

    Any help would be greatly appreciated. Thanks.

    Thanks

  41. John says:

    Hi - I sorted the problem. I was just being a muppet and it all works beautifully. I changed the relationship from HABTM to Product has Many Images (which is fine as I plan to use the polymorphic behaviour to attach multiple models).

    I also changed the controller from:
    $this->Product->save($this->data)
    to
    $this->Product->saveAll($this->data)

    Thanks.

  42. gabriel says:

    Hi,

    I have problem with validation :
    preg_match() expects parameter 2 to be string, array given [/homez.40/.../cakephp/cake/libs/validation.php, line 877]

    See you

    Gabriel

  43. gabriel says:

    I have solved the problem with validation : you have to use PHP5 and I used PHP4

  44. Noel says:

    Hello !

    I’d like to say that this project helped me a lot in my own.
    But I’m facing a small problem now :
    I can’t delete the files I uploaded via the checkbox.
    When I put the file to delete in the input, check the box, a new entry is inserted in my DB.

    Can anyone tell me what’s the problem ?

    Thanks in advance.

  45. John says:

    Hi Vinicius. I’ve been playing around trying to upload multiple files at the same time - i.e. Product has many ProductImages - in order to save the images I’m using the following in my controler:

    function admin_add() {
    if (!empty($this->data)) {
    $this->Product->create();

    if ($this->Product->save($this->data)) {

    $product_id = $this->Product->getLastInsertId();

    // this is multiple images
    foreach($this->data['ProductImage'] as $ProductImage => $value){

    $this->Product->ProductImage->create();
    $value['product_id'] = $product_id;
    $this->Product->ProductImage->save($value);
    }

    $this->Session->setFlash(__(’The Product has been saved’, true));
    $this->redirect(array(’action’=>’index’));

    } else {
    $this->Session->setFlash(__(’The Product could not be saved. Please, try again.’, true));
    }
    }
    }

    The $this->data array would look like this:


    Array
    (
    [Product] => Array
    (
    [name] => Product 0
    [live] => 1
    )

    [ProductImage] => Array
    (
    [0] => Array
    (
    [filename] => Array
    (
    [name] => doves.jpg
    [type] => image/jpeg
    [tmp_name] => E:\xampp\tmp\php7A.tmp
    [error] => 0
    [size] => 21024
    )

    )

    [1] => Array
    (
    [filename] => Array
    (
    [name] => 2960-medium.jpg
    [type] => image/jpeg
    [tmp_name] => E:\xampp\tmp\php7B.tmp
    [error] => 0
    [size] => 134256
    )

    )

    )

    )

    But I was wondering if there was a better way of dealing with this? You mentioned in one of the comments above that you were planning to put up an example of uploading multiple files.

    What I’ve done it above is fine but it would be so much more elegant to push it into the behaviour.

    Cheers

  46. 唯枫志 - CakePHP中使用MeioUpload Behavior上传图片 says:

    [...] 这款MeioUpload Behavior真是帮我解决了大问题,感谢作者和阿辉,另外CakePHP的app/models/behaviors目录是专门用来存放相关行为处理文件的,大家如果想省事儿,可以到http://bakery.cakephp.org/来先找找有没有人事先写好的代码,记录下图片上传先。 我的文章表里有两个字段:thumbnailimg 和 largeimg ,分别代表小图和大图,文章添加时上传的两张图片到webroot/files/images下,并把路径和文件名分别保存到这两个字段,实现过程如下: [...]

Leave a Reply