06.26
php
saved
Linnk
Note
A smart file upload behavior which uses mime-types to sort and validate files based on criteria set by the user. Use it in your model like this:
A smart file upload behavior which uses mime-types to sort and validate files based on criteria set by the user. Use it in your model like this:
var $actsAs = array(
'File' => array(
'image' => array(
'/image\/(jpeg|gif|png)/' => array(
'destination' => 'files/images/',
'naming' => 'hash',
'max' => 1024 * 1024
)
),
'document' => array(
'/application\/pdf/' => array(
'destination' => 'files/pdfs/',
'naming' => 'hash',
'max' => 1024 * 1024 * 1024
)
)
)
);
function hash(&$data) {
return sha1_file($data['tmp_name']);
}
- <?php
- class FileBehavior extends ModelBehavior {
- 'destination' => 'files/',
- 'max' => 0,
- 'naming' => 'hash'
- )
- );
- }
- $this->settings[$Model->alias],
- );
- }
- function beforeSave(&$Model) {
- foreach ($this->settings[$Model->alias] as $field => $types) {
- foreach ($types as $pattern => $options) {
- $supported = true;
- $name = $Model->{$options['naming']}(&$Model->data[$Model->alias][$field]);
- if ($options['max'] > 0 && $Model->data[$Model->alias][$field]['size'] >= $options['max']) {
- $Model->invalidate($field, __('Sorry, this file is too big.', true));
- return false;
- }
- $path = WWW_ROOT . $options['destination'] . $name;
- $Model->data[$Model->alias][$field] = $options['destination'] . $name;
- } else {
- $Model->invalidate($field, __('Sorry, the file could not be uploaded.', true));
- return false;
- }
- break;
- }
- }
- if (!$supported) {
- $Model->invalidate($field, __('Sorry, this file type is not supported.', true));
- }
- }
- }
- }
- ?>
Parsed in 0.097 seconds, using GeSHi 1.0.7.14