Skip to content

szajbus/uploadpack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

UploadPack

UploadPack is a plugin that makes file uploads in CakePHP as easy as possible. It works with almost no configuration, but if you need more flexibility you can easily override default settings.

What’s included:

UploadBehavior

Attach it to your model, it will detect any uploaded file and save it to disk. It can even automatically generate thumbnails of uploaded images.

UploadHelper

Use it in your views to display uploaded images or links to files in general.

Installation

  1. Download this: http://github.com/szajbus/uploadpack/zipball/master
  2. Unzip that download.
  3. Copy the resulting folder to app/plugins
  4. Rename the folder you just copied to upload_pack

Usage

Look at an example.

Scenario: Let users upload their avatars and then display them in two styles – original size and thumbnail.

Solution:

We’ll need User model with avatar_file_name field.

CREATE table users (
	id int(10) unsigned NOT NULL auto_increment,
	login varchar(20) NOT NULL,
	avatar_file_name varchar(255)
);

Attach UploadBehavior to User model and set it up to handle avatars.

<?php
	class User extends AppModel {
		var $name = 'User';
		var $actsAs = array(
			'UploadPack.Upload' => array(
				'avatar' => array(
					'styles' => array(
						'thumb' => '80x80'
					)
				)
			)
		);
	}
?>

That’s all we need to do with our model. We defined one thumbnail style named ‘thumb’ which means that uploaded image’s thumnbnail of 80×80 pixels size will be generated and saved to disk together with original image.

We didn’t touch any other configuration settings so files will be saved as webroot/upload/:model/:id/:basename_:style.:extension (with :keys appropriately substituted at run time). Make sure that webroot/upload/users folder is writeable.

Let’s upload a file now. We need to add a file field to a standard “create user” form. Your form must have the right enctype attribute to support file uploads, e.g. $form->create('Users', array('type' => 'file'));. Note that we omit the field’s _file_name suffix here.

<?php echo $form->file('User.avatar') ?>

The last thing to do is to handle form-submit in a controller.

<?php
class UsersController extends AppController {
	var $name = 'Users';
	var $uses = array('User');
	var $helpers = array('Form', 'UploadPack.Upload');

	function create() {
		if (!empty($this->data)) {
			$this->User->create($this->data);
			if ($this->User->save()) {
				$this->redirect('/users/show/'.$this->User->id);
			}
		}
	}

	function show($id) {
		$this->set('user', $this->User->findById($id));
	}
}
?>

Let’s create users/show.ctp view to see the results. Note that we’ve included UploadHelper in controller’s $helpers.

That would be the original file:
<?php echo $this->Upload->uploadImage($user, 'User.avatar') ?>

And now it's thumbnail:
<?php echo $this->Upload->uploadImage($user, 'User.avatar', array('style' => 'thumb')) ?>

That’s how you create new records with uploaded files. Updating existing record would delete a file attached to it from disk.

Could it be any easier? Probably not. Is there more to offer? Yes.

Advanced configuration

You can validate uploaded files

UploadBehavior provides some validation rules for you to use together with standard CakePHP validation mechanism.

Validate attachment’s size:

var $validate = array(
	'avatar' => array(
		'maxSize' => array(
			'rule' => array('attachmentMaxSize', 1048576),
			'message' => 'Avatar can\'t be larger than 1MB'
		),
		'minSize' => array(
			'rule' => array('attachmentMinSize', 1024),
			'message' => 'Avatar can\'t be smaller than 1KB'
		)
	)
);

Validate attachment’s content type:

var $validate = array(
	'avatar' => array(
		'image1 => array(
			'rule' => array('attachmentContentType', 'image/jpeg'),
			'message' => 'Only jpegs please'
		),
		'image2' => array(
			'rule' => array('attachmentContentType', array('image/jpeg', 'image/gif')),
			'message' => 'Only jpegs or gifs please'
		),
		'image3' => array(
			'rule' => array('attachmentContentType', array('document/pdf', '/^image\/.+/')),
			'message' => 'Only pdfs or images please'
		)
	)
);

Validate attachment’s presence:

var $validate = array(
	'avatar' => array(
		'rule' => array('attachmentPresence'),
		'message' => 'Avatar is required'
	)
);

Validate image size:

var $validate = array(
	'avatar' => array(
		'minWidth' => array(
			'rule' => array('minWidth', '100'),
			'message' => 'Photo must be at least 100 pixels wide'
		),
		'maxWidth' => array(
			'rule' => array('maxWidth', '600'),
			'message' => 'Photo can\'t be over 600 pixels wide'
		),
		'minHeight' => array(
			'rule' => array('minHeight', '100'),
			'message' => 'Photo must be at least 100 pixels wide'
		),
		'maxHeight' => array(
			'rule' => array('maxHeight', '600'),
			'message' => 'Photo can\'t be over 600 pixels wide'
		)
	)
);

If you’re editing a record that already has avatar attached and you don’t supply a new one, record will be valid.

Validate php upload errors:
PHP: Error Messages Explained – Manual (http://www.php.net/manual/features.file-upload.errors.php)

var $validate = array(
	'avatar' => array(
		'checkIniSizeError' => array(
			'rule' => array('phpUploadError', UPLOAD_ERR_INI_SIZE),
			'message' => 'The uploaded file exceeds the upload_max_filesize directive in php.ini'
		),
		'checkSizesError' => array(
			'rule' => array('phpUploadError', array(UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE)),
			'message' => 'The uploaded file exceeds the upload_max_filesize directive in php.ini or MAX_FILE_SIZE directive that was specified in the HTML form'
		),
		'checkAllError' => array(
			'rule' => array('phpUploadError'),
			'message' => 'Can\'t upload'
		)
	)
);

Validation options:

You can pass additional options to validation rules:

  • allowEmpty – if set to false will cause validation to fail if the file is not present. This option is not available for attachmentPresence rule.

The example below return true if there is no upload files or jpeg.

var $validate = array(
	'avatar' => array(
		'rule' => array('attachmentContentType', 'image/jpeg'),
		'message' => 'Only jpegs please',
		'allowEmpty' => true
	)
);

You can change the path where the files are saved

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(
			'path' => 'your/new/path'
		)
	)
);

The path string can contain special :keys that will be substituted at run time with appropriate values. Here’s the list of available :keys with the values they’re substituted with.

  • :app – path to your app dir
  • :webroot – path to your app’s webroot dir
  • :model – name of the model tableized with Inflector::tableize (would be ‘users’ for User model)
  • :id – ID of the record
  • :basename – basename of the uploaded file’s original name (would be ‘photo’ for photo.jpg)
  • :extension – extension of the uploaded file’s original name (would be ‘jpg’ for photo.jpg)
  • :style – name of the thumbnail’s style
  • :attachment – pluralized name of the attachment (for example ‘avatars’)
  • :hash – md5 hash of the original filename + Security.salt

Default value for path is :webroot/upload/:model/:id/:basename_:style.:extension.

You can change the url the helper points to when displaying or linking to uploaded files

This setting accepts all the :keys mentioned above and it’s default value depends on path setting. For default path it would be defaults /upload/:model/:id/:basename_:style.:extension.

You probably won’t need to change it too often, though.

You can point to default url if the uploaded file is missing

If uploading an avatar is only a option to your users, you would probably want to have some default image being displayed if no image is uploaded by a user.

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(
			'default_url' => 'path/to/default/image'
		)
	)
);

This setting accepts all the :keys mentioned above, but it’s not set by default which results in usual url being returned even it the file does not exist.

You can choose to automatically scale down images that are wider than the maxWidth specified in validation.

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(
			'resizeToMaxWidth' => true
		)
	)
);

JPEG Quality

The jpeg quality can be set with the quality setting.

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(
			'quality' => 95
		)
	)
);

Alpha Channel(PNG, GIF only)

The png and gif can use alpha channel alpha setting.

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(
			'alpha' => true
		)
	)
);

You can choose another field for an external url

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(
			'urlField' => 'gravatar'
		)
	)
);

This way the user can paste an url or choose a file from their filesystem. The url will mimick usual uploading so it will still be validated and resized.

Deleting a file attached to field

$model->data['avatar'] = null;
	$model->save();

More on styles

Styles are the definition of thumbnails that will be generated for original image. You can define as many as you want.

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(
			'styles' => array(
				'big' => '200x200',
				'small' => '120x120',
				'thumb' => '80x80'
			)
		)
	)
);

Be sure to have :style key included in your path setting to differentiate file names. The original file is also saved and has ‘original’ as :style value, so you don’t need it to define it yourself.

If you want non-image files to be uploaded, define no styles at all. It does not make much sense to generate thumbnails for zip or pdf files.

You can specify any of the following resize modes for your styles:

  • 100×80 – resize for best fit into these dimensions, with overlapping edges trimmed if original aspect ratio differs
  • [100×80] – resize to fit these dimensions, with white banding if original aspect ratio differs (Michał’s original resize method)
  • 100w – maintain original aspect ratio, resize to 100 pixels wide
  • 80h – maintain original aspect ratio, resize to 80 pixels high
  • 80l – maintain original aspect ratio, resize so that longest side is 80 pixels

More on database table structure

The only database field you need to add to your model’s table is [field]_file_name. Replace [field] with chosen name (avatar for example).

There are two optional fields you can add: [field]_content_type and [field]_file_size. If they’re present they will be populated with uploaded file’s content type and size in bytes respectively.

Model can have many uploaded files at once. For example define two fields in database table: avatar_file_name and logo_file_name. Set up behavior:

var $actsAs = array(
	'UploadPack.Upload' => array(
		'avatar' => array(),
		'logo' => array()
		)
	)
);

Using the helper

There are two methods of UploadHelper you can use:

UploadHelper::uploadUrl($data, $field, $options = array())

Returns url to the uploaded file

  • $data – record from database (would be $user here)
  • $field – name of a field, like this Modelname.fieldname (would be User.avatar here)
  • $options – url options
    • ‘style’ – name of a thumbnail’s style
    • ‘urlize’ – if true returned url is wrapped with $html->url()

UploadHelper::uploadImage($data, $field, $options = array(), $htmlOptions = array())

Returns image tag pointing to uploaded file.

  • $data – record from database (would be $user here)
  • $field – name of a field, like this Modelname.fieldname (would be User.avatar here)
  • $options – url options
    • ‘style’ – name of a thumbnail’s style
    • ‘urlize’ – if true returned url is wrapped with $html->url()
  • $htmlOptions – array of HTML attributes passed to $html->image()

Assuming that you have read a user from database and it’s available in $user variable in view.

<?php echo $this->Upload->uploadImage($user, 'User.avatar', array('style' => 'thumb')); ?>

When you fetch user from database you would usually get:

$user = array(
	'User' => array(
		'id' => 1,
		'avatar_file_name' => 'photo.jpg'
	)
);

But when the user is fetched as one of many users associated by hasMany association to another model it could be something like:

$data = array(
	'User' => array(
		0 => array(
			'id' => 1,
			'avatar_file_name' => 'photo.jpg'
		),
		1 => array(
			'id' => 2,
			'avatar_file_name' => 'photo2.jpg'
		)
	)
);

Then you should do:

<?php echo $this->Upload->uploadImage($data['User'][0], 'User.avatar', array('style' => 'thumb')) ?>

The helper is smart enough to figure out the structure of data you pass to it.

Requirements

UploadPack was developed with CakePHP 1.2 RC3, so it’s not guaranteed to work with previous versions. You’ll need GD library if you plan to generate image thumbnails. It works OK with 2.0.34 version at least, earlier versions may work too.

Plans for future

There is still something missing in UploadPack, here’s what will be added soon:

  • file name normalization

The plans for more distant future:

  • test coverage
  • allow uploads to S3
  • provide a method to regenerate all thumbnails, helpful if you later decide to have different sizes of thumbnails or more styles

I you want to help implementing these features, feel free to submit your patches.

Copyright

Copyright © 2008 Michał Szajbe (http://codetunes.com), released under the MIT license.

joe bartlett’s (http://jdbartlett.com) tweaks aren’t under copyright. Run free, little tweaks!

About

Easy way to handle file uploads in CakePHP.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages