Add image with uploader



Display an image on the page and allow to upload
-> Stores the image in the database

# 1 > Display image

Add the following code to
-> Display the image
-> Allow to upload a new version

The code ensures no errors when the database is not setup yet

    
<?= $this->Form->input('image_upload', array(
'type' => 'file',
'label' => 'Image Upload')); ?>

<?php if (isset($this->data[$model])): if (!empty($this->data[$model]['image'])): ?>
<img src="data:<?= $this->data[$model]['image_mime']; ?>;base64,<?= base64_encode($this->data[$model]['image']); ?>"
width="100%">
<?php endif; endif; ?>


# 2 > Modify FORM create

Ensure the Form create has 

'type' => 'file'

It should look like this

<?= $this->Form->create($model, array(
'type' => 'file'
)); ?>

# 3 > Create a function to process the file

Create an new function that will process the file on save

private function handleFiles($model, $imageColumn = 'image', $imageMimeColumn = 'image_mime') {
if (!empty($this->request->data[$model]['image_upload']['tmp_name'])) {
$this->request->data[$model][$imageColumn] = file_get_contents($this->request->data[$model]['image_upload']['tmp_name']);
$this->request->data[$model][$imageMimeColumn] = $this->request->data[$model]['image_upload']['type'];
}
}

 


# 4 > Modify EDIT

In the edit action of the controller ensure after the if $this->request->data we need to call our 'handleFiles()'

if (!empty($this->request->data)) {
$this->handleFiles($model);
...

Other Instructions

Below are many other instructions that show you how to use your UpdateCase application