Uploadプラグインの中でも評価の高かった、
https://github.com/josegonzalez/cakephp-upload
これを実装してみたのでメモ。
オプションも多く、使いやすそう。
今回使ったのは、以下のオプション。
'path' => '{ROOT}webroot{DS}files{DS}thumb{DS}',
'fields' => array(
'dir' => 'image_directry',
),
'thumbnailSizes' => array(
'xvga' => '1024x768',
'vga' => '640x480',
'cubic' => '200x200',
'thumb' => '80x80'
)
'path'
画像の格納パス。この場合はアップロードされた画像はwebroot/files/thumb/~
'fields'
画像名が入るDBフィールド。
'thumbnailSizes'
thumbnailSizeを使っうとそれぞれのサイズが{size-name}_file_name で生成。
サイズ指定のオプションは以下。
100×80 – アスペクト比を保ち、トリミングを行う
[100×80] – 指定したアスペクト比にフィットさせる
100w – アスペクト比を保ち、幅100px
80h – アスペクト比を保ち、縦80px
その他にも、画像のサイズの最大・最小値の指定やパーミッション、上書きの可否等も指定できるようだ。
また細かいバリデーションをかけてエラーメッセージの指定も可能。
例:
public $validate = array(
'image' => array(
'isUnderPhpSizeLimit' => array(
'rule' => 'isUnderPhpSizeLimit',
'message' => 'File exceeds upload filesize limit'
),
'isCompletedUpload' => array(
'rule' => 'isCompletedUpload',
'message' => 'File was not successfully uploaded'
),
'tempDirExists' => array(
'rule' => 'tempDirExists',
'message' => 'The system temporary directory is missing'
),
'isFileUploadOrHasExistingValue' => array(
'rule' => 'isFileUploadOrHasExistingValue',
'message' => 'File was missing from submission'
),
'isWritable' => array(
'rule' => array('isWritable'),
'message' => 'File upload directory was not writable'
),
'isValidDir' => array(
'rule' => array('isValidDir'),
'message' => 'File upload directory does not exist'
),
'isBelowMaxSize' => array(
'rule' => array('isBelowMaxSize', 1024),
'message' => 'File is larger than the maximum filesize'
),
'isValidExtension' => array(
'rule' => array('isValidExtension', array('pdf', 'png', 'txt')),
'message' => 'File does not have a pdf, png, or txt extension'
),
)
);
Ex
簡単に実装テスト。テーブル構成がこんな感じで
CREATE table users (
id int(10) unsigned NOT NULL auto_increment,
username varchar(20) NOT NULL,
image varchar(255)
image_directry varchar(255)
);
Userクラスには、$actsAsを追加。
public $actsAs = array(
'Upload.Upload' => array(
'image' => array(
'path' => '{ROOT}webroot{DS}files{DS}thumb{DS}',
'fields' => array(
'dir' => 'image_directry',
),
'thumbnailSizes' => array(
'xvga' => '1024x768',
'vga' => '640x480',
'cubic' => '200x200',
'thumb' => '80x80'
)
)
)
コントローラではadd functionを持っているものとします。
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
ビューはこんな感じ。
Form->create('User', array('type' => 'file')); ?>
Form->input('username'); ?>
Form->input('image', array('type' => 'file')); ?>
Form->input('image_directry', array('type' => 'hidden')); ?>
Form->end(); ?>