LoginSignup
13
11

More than 5 years have passed since last update.

CakePHPのフォームで画像ファイルを選択後にサムネイル画像を表示させる方法

Last updated at Posted at 2015-02-02

JSの準備

Layouts/default.ctp等に下記JSを記述。

<script>
$(function() {
    // アップロードするファイルを選択
    $('input[type=file]').change(function() {
    var file = $(this).prop('files')[0];

    // 画像以外は処理を停止
    if (!file.type.match('image.*')) {
        $('span').html('');
       return;
    }

    // 画像表示
    var reader = new FileReader();
        reader.onload = function() {
        var img_src = $('<img>').attr({'src': reader.result, 'width': '150px'});
            $('p').html(img_src);
        };
       reader.readAsDataURL(file);
    });
});
</script>

テンプレート(ctp)ファイルの準備

下記のようなformを用意する。

form.ctp
<?php
$options = array(
    'action' => 'done',
    'type' => 'file',
    'inputDefaults' => array('legend' => false, 'label' => false, 'div' => false),
    'class' => 'form-horizontal'
);
?>
<?php echo $this->Form->create(false, $options); ?>
<!-- 画像ファイル指定 -->
<div class="control-group">
<label class="control-label" for="fileInput">画像</label>
<div class="controls">
<?php echo $this->Form->file('Hoge.image', array('id' => 'fileInput', 'class' => 'input-file uniform_on')); ?>
</div>
</div>
<!-- サムネイル画像表示 -->
<div class="control-group">
<label class="control-label" for="fileInput">サムネイル画像</label>
<div class="controls">
<p>指定なし</p>
</div>
</div>
<?php echo $this->Form->end(); ?>

画像を選択後、サムネイル画像表示領域に選択した画像が表示される。

13
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11