2

I am trying to upload image using cakephp 3. I tried it in cake 2.x, it worked fine there but not in cake 3.0. My image is uploaded but it is not getting saved in DB.

view

<div class="col-lg-8">
<div class="articles form large-9 medium-8 columns content">
    <?= $this->Form->create($article,['type' => 'file']) ?>
    <fieldset>
        <legend><?= __('Add Article') ?></legend>
        <?php
        echo $this->Form->input('title', [ "class" => "form-control"]);

        echo $this->Form->input('body', [ "class" => "form-control"]);

        echo $this->Form->file('image',[ "class" => "form-control"]);
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit'), ["class" => "btn btn-primary"]) ?>
    <?= $this->Form->end() ?>
</div>

Controller

public function add() {
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {
        $filepath = getcwd() . '/uploads/' . $this->request->data['image']['name'];
        $filename = $this->request->data['image']['name'];
        $article = $this->Articles->patchEntity($article, $this->request->data);
        if ($this->Articles->save($article)) {                
            move_uploaded_file($this->request->data['image']['tmp_name'], $filepath);
            $this->Flash->success(__('The article has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The article could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('article'));
    $this->set('_serialize', ['article']);
}

Model

namespace App\Model\Table;

use App\Model\Entity\Article;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class ArticlesTable extends Table {
public function initialize(array $config) { parent::initialize($config);

    $this->table('articles');
    $this->displayField('title');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->hasMany('Comments', [
        'foreignKey' => 'article_id'

    ]);
}


public function validationDefault(Validator $validator)
{
    $validator
        ->add('id', 'valid', ['rule' => 'numeric'])
        ->allowEmpty('id', 'create');

    $validator
        ->allowEmpty('title');

    $validator
        ->allowEmpty('body');

    $validator
        ->add('image', [
                    'fileSize' => [
                            'rule' => [
                                'fileSize', '<', '5MB'
                            ],
                            'message' => 'Please upload file smaller than 5MB'
                        ],
                    'mimeType' => [
                        'rule' => [
                            'mimeType', ['image/jpeg','image/png','image/jpg']
                        ],
                        'message' => 'Please upload only png images'
                    ]
                ]
        )
        ->requirePresence('image', 'create')
        ->notEmpty('image');
    return $validator;
}

}

4
  • The "image" field of your input is an array with various keys in it. What sort of field do you have in your articles table for saving that? Commented Feb 4, 2016 at 15:47
  • The field name I am using in articles table is 'image'. Commented Feb 5, 2016 at 4:43
  • What kind of field is it? A varchar for the file path? A blob for the actual image data? Either way, you are receiving an array of other values and, based on the code you've shown, not doing anything to change that. Commented Feb 5, 2016 at 15:26
  • I have a found a solution for my problem. Thank you all for your valuable replies. Commented Feb 6, 2016 at 8:27

1 Answer 1

3

I have found a solution myself but I am not sure whether it is the right way. But by doing this my problem has been solved.

public function add() {
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {
        $imageName = $this->request->data['image']['name'];
        $filepath = getcwd() . '/uploads/' . $imageName;
        $article = $this->Articles->patchEntity($article, $this->request->data);
        $article->image =  $imageName ;

        if ($this->Articles->save($article)) {                
            move_uploaded_file($this->request->data['image']['tmp_name'], $filepath);
            chmod($filepath, 0777);
            $this->Flash->success(__('The article has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The article could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('article'));
    $this->set('_serialize', ['article']);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, that's the kind of change that I was talking about.
this will work but custom model validation will not work here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.