#CakePHP file upload behavior
File uploading is a very common task in building applications, to handle it from model level, we have came up with a file model behavior, which is able to handle file uploads automatically.
Before you start reading, make sure you have good understanding of CakePHP behavior, and at least have experience using CakePHP behavior. If not, we recommend you to read Cook Book behavior first.
In this tutorial we will introduce you our file model behavior as well as how to use it for you CakePHP application.
#File Model behavior
- File Model behavior is a CakePHP behavior which is able to handle file uploading automatically, you can download the behavior here.
- A simple code explaination of this behavior. It will upload file in afterSave() callback, where it takes current save model's id as the folder name, then upload it into directory related to "app/webroot" using the original file name.
- Some notes to take before using this behavior:
- It uses the original file name.
- It stores file in directory: "app/webroot/" + Configured sub directory(default is uploads) + Model id folder + file name
#Preparation
#How to use
- Since File Model behavior stores file name inside database, so you will need to have a database table for this behavior to work.
Create a database table:
CREATE TABLE `photos` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`filename` VARCHAR( 250 ) NOT NULL
) ENGINE = MYISAM ;
- Place your downloaded file_model.php into "app/models/behaviors/file_model.php".
- Create your photo model and include File Model behavior:
<?php
class Photo extends AppModel {
public $actsAs = array('FileModel');
}
?>
If you don't supply any parameters to the behavior, it will try to detect files from $this->data['Photo']['file'], store file name inside database table's "filename" attribute and store file inside directory "app/webroot/uploads".
- Now if you call $this->Photo->save($data) from anywhere, it will save the file automatically. And it will delete the file if you call $this->Photo->delete($data).
Remember to set form "type"=>"file" for the upload form in view file.
#Customization
- There are three pamameters you can config while using File Model behavior as below:
public $actsAs =
array('FileModel'=>
array(
'dir'=>array(''),
'file_field'=>array(''),
'file_db_file'=>array('')
)
);
- Set value of "dir" to customize the uploading directory, remember this direcotry is related to "app/webroo", by default, its value is "uploads".
- Set value of "file_field" to customize the uploading data field passed from form, by default, its value is "file".
- Set value of "file_db_file" to customize your database table field which will store the file name , by default, its value is "filename".