Samcar
Samcar

Reputation: 23

File Upload CakePHP 3.4

Im trying to get a simple file upload from a form to save in my webroot/img folder, however i'm having some difficulty.

This is the form in the view:

<?= $this->Form->create($productImage) ?>
<fieldset>
    <legend><?= __('Add Product Image') ?></legend>
    <?php
        echo $this->Form->control('product_id', ['options' => $products]);
        echo $this->Form->file('image', ['label' =>'','size'=>'50']); //Uploaded file
        echo $this->Form->control('image_path');
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

And this is the function in the controller:

    public function add()
{
    $productImage = $this->ProductImages->newEntity();
    if ($this->request->is('post')) {
        $image = $this->request->data['image'];
        if (move_uploaded_file($image,WWW_ROOT . '/img')) {
            $this->Flash->success(__('file upload successful'));
        } else {
            $this->Flash->success(__('file upload unsuccessful'));
        }
        $productImage = $this->ProductImages->patchEntity($productImage, $this->request->getData());

        if ($this->ProductImages->save($productImage)) {
            $this->Flash->success(__('The product image has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The product image could not be saved. Please, try again.'));
    }
    $products = $this->ProductImages->Products->find('list', ['limit' => 200]);
    $this->set(compact('productImage', 'products'));
    $this->set('_serialize', ['productImage']);
}

move_uploaded_file keeps returning false, and I cant work out why.

Thanks a lot for any help.

Sam.

Upvotes: 2

Views: 2248

Answers (1)

tarikul05
tarikul05

Reputation: 1913

You have to care 2 things

1.Proper from declaration

Add enctype="multipart/form-data" in your html form ( ['type' => 'file']) in CakePHP form create to the. then your code will be

<?= $this->Form->create($productImage,['type' => 'file']) ?>
Details Here

2. Upload image

Upload Image in proper way using
$this->request->data['image']['name'];

Upvotes: 2

Related Questions