LoginSignup
16
18

More than 5 years have passed since last update.

CakePHP3.x でDBに画像を保存&表示

Last updated at Posted at 2015-05-21

2系と結構変わってて表示させるのに苦労しました

  • JPEGファイルの保存と表示を例にしています(カラム名はthumbnail)
  • 追加時は画像必須、編集時は指定しなければ画像を更新しない想定です
  • JPEGのValidation例はこちら(Qiita)

データの保存

Table

  • 保存前にtmp_nameからデータを読み込み実データを渡しています
  • なんとなくメソッドの形をCookbookに合わせてます
src/Model/Table/HogeTable.php
use RuntimeException;

    public function beforeSave($event, $entity, $options)
    {
        if ($entity->thumbnail['error'] === UPLOAD_ERR_OK) {
            $entity->thumbnail = $this->_buildThumbnail($entity->thumbnail);
        } else {
            unset($entity->thumbnail);
        }
    }

    protected function _buildThumbnail($thumbnail)
    {
        $ret = file_get_contents($thumbnail['tmp_name']);
        if ($ret === false) {
            throw new RuntimeException('Can not get thumbnail image.');
        }

        return $ret;
    }

表示

Controller側

  • アクセスはcontents/{id}としています
  • $this->autoRender = false でrender処理を止めておきます
  • DBからデータを取得した状態では、当該カラムは ストリームリソース型 になっている為、stream_get_contents関数で読み込みます
src/Controller/HogeController.php
    public function contents($id)
    {
        $data = $this->HogeDatas->get($id);
        $this->autoRender = false;
        $this->response->type('image/jpeg');
        $this->response->body(stream_get_contents($data->thumbnail));
    }

View側

  • HtmlHelper#imageを使うとURLの階層が上手くいかないのでとりあえずUrlHelper#buildのみ使用しています
src/Template/HogeDatas/edit.ctp
        <img src="<?= $this->Url->build(["controller" => "HogeDatas", "action" => "contents", $hogeData->id]); ?> " />
16
18
1

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
16
18