百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
U

uploadpack

> 编程语言
开源

在 CakePHP 中轻松处理文件上传。

99 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

在 CakePHP 中轻松处理文件上传。

h1. UploadPack

"!https://pledgie.com/campaigns/7880.png?skin_name=chrome!(Using it in production? Share some love...)":https://www.pledgie.com/campaigns/7880

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:

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

h4. UploadHelper

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

h2. Installation

Download this: http://github.com/szajbus/uploadpack/zipball/master

Unzip that download.

Copy the resulting folder to app/plugins

Rename the folder you just copied to upload_pack

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

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 80x80 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.

file('User.avatar') ?>

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

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: Upload->uploadImage($user, 'User.avatar') ?>

And now it's thumbnail: 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.

h3. Advanced configuration

h4. 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 ) );

h4. 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@.

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

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

h4. 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 ) ) );

h4. JPEG Quality

The jpeg quality can be set with the quality setting.

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

h4. 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 ) ) );

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

h4. Deleting a file attached to field

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

h3. 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:

  • 100x80 - resize for best fit into these dimensions, with overlapping edges trimmed if original aspect ratio differs
  • [100x80] - 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

h3. 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() ) ) );

h3. Using the helper

There are two methods of UploadHelper you can use:

h4. 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()@

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

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

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHP

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言