Last active
December 19, 2017 06:15
-
-
Save hossshy/e9e727ce83e22e935e09 to your computer and use it in GitHub Desktop.
CakePHP3.x でDBに画像を保存&表示 ref: https://qiita.com/kazamai/items/fdb6324fcb78e1865dd1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<img src="<?= $this->Url->build(["controller" => "HogeDatas", "action" => "contents", $hogeData->id]); ?> " /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment