cakephpcakephp-3.1cakephp-3.x

File fails to upload when using xety/cake3-upload plugin


I am not able to upload a file from one folder to another in CakePHP. Here is my code.

First I loaded the plugin and added this code in ProductsTable.php

$this->addBehavior('Xety/Cake3Upload.Upload', [
    'fields' => [
        'productimg_file' => [
            'path' => 'uploads/avatar/:id/:md5'
        ]
    ]
]);

then I added in my add.cpt

<?php
    echo $this->Form->input('productcode');
    echo $this->Form->input('productname');
    echo $this->Form->input('productprice');
    echo $this->Form->input('quantity');
    echo $this->Form->input('productdesc');
    echo $this->Form->input('productimg_file',['type' => 'file']);
?>

Still the file doesn't get moved to the webroot dir.

public function add() {
    $product = $this->Products->newEntity();
    if ($this->request->is('post')) {
        $product = $this->Products->patchEntity($product, $this->request->data);
        if ($this->Products->save($product)) {
            $this->Flash->success(__('The product has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The product could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('product'));
    $this->set('_serialize', ['product']);
}

Solution

  • I have uploaded successfully by that plugin. At beginning, I was your error but I fixed it. Here my steps...

    Within: CakePHP 3.2 Red Velvet

    1. Download source Copy UploadBehavior.php to /src/Model/Behavior

    2. Copy "xety/cake3-upload": "1.*" (with the double quote "") paste to /config/bootstrap.php in the "require-dev": {...},

    Ex:

    "require-dev": {
            "psy/psysh": "@stable",
            "cakephp/debug_kit": "~3.2",
            "cakephp/bake": "~1.1",
            "xety/cake3-upload": "1.*"
        },
    
    1. open terminal (window cmd) type:

      composer update

    Note: if you don't have composer, google and install it.

    => I knew number 1 and 2 are same, but I made it for sure.

    1. Config as plugin manual. This below config was in Model/Table/model_nameTable.php NOT Model/Entity/model.php

    Ex:

    $this->addBehavior('Xety/Cake3Upload.Upload', [
            'fields' => [
                'avatar' => [
                    'path' => '/img/avatars/:id/:md5'
                        ]
                    ]
                ]
            );
    
    1. Set the update URL with

      '/img/folder_name/:id/:md5'

    Ex:

    '/img/avatars/:id/:md5'
    
    1. Make sure the FORM in view is define as:

      $this->Form->create($user, ['enctype' => 'multipart/form-data'])

    and input file was correct name:

    $this->Form->file('fieldname_file');
    

    Ex:

    $this->Form->file('avatar_file');
    

    Not need to call anything from controller, when you submit form, it will uploaded automatically.

    Good luck !