【CakePHP2, jQuery】Ajaxで画像をアップロードする
CakePHP2のFormヘルパーとjQueryを使って、画像ファイルをアップロードしてみます。アップロード時に画像名を付けて保存できるようにします。
以下、最低限の処理しか書いていません。本番では、ファイル名チェックなどのセキュリティ対策が必要です。
- CakePHP
- 2.8.0
- jQuery
- 2
Formヘルパーを使ってFormをつくる
<?php
echo $this->Form->create('Image',array('action' => 'add', 'type' => 'file')).PHP_EOL;
echo $this->Form->input(false,array(
'type' => 'file',
'label' => '画像選択',
)).PHP_EOL;
echo $this->Form->input('fileName', array(
'type' => 'text',
'label' => '画像名',
'required' => true,
)).PHP_EOL;
echo $this->Form->submit('upload',array('id' => 'img')).PHP_EOL;
echo $this->Form->end().PHP_EOL;
?>
コントローラー
<?php
App::uses('AppController', 'Controller');
class ImagesController extends AppController
{
public function add()
{
if (!empty($this->request->data) && $this->request->is('ajax')) {
Configure::write('debug',0);
$this->autoRender = false;
$this->autoLayout = false;
$type = array(
'image/png' => '.png',
'image/jpeg' => '.jpg',
'image/gif' => '.gif',
);
$fileName = $this->request->data['Image']['fileName']. $type[$this->request->data['Image']['type']];
move_uploaded_file($this->request->data['Image']['tmp_name'], /ファイルの保存場所/. $fileName);
$params = array(
'Image' => array(
'name' => $fileName
)
);
if ($this->Image->save($params)) {
return $fileName;
} else {
return 'error';
}
}
exit();
}
}
JavaScript
$(function()
{
$("#ImageAddForm").submit(function()
{
var fd = new FormData($(this)[0]);
$.ajax({
type: 'post',
url: "/images/add",
data: fd,
processData: false,
contentType: false,
});
return false;
});
});
おわりに
モデルは省略しています。
以上でフォームから画像を上げることができるようになりました。
最低限の処理しか書いていませんが、これらにエラー処理やコントローラーでサイズ取得などの処理を追加していきます。